0
0
Raspberry Piprogramming~5 mins

systemd service for auto-start in Raspberry Pi

Choose your learning style9 modes available
Introduction

We use a systemd service to make a program start automatically when the Raspberry Pi turns on. This helps run important tasks without needing to start them by hand.

You want a script to run every time your Raspberry Pi boots up.
You have a server program that should always be running in the background.
You want to start a sensor reading program automatically after power on.
You need to run a backup script every time the device restarts.
You want to launch a web server or app without manual intervention.
Syntax
Raspberry Pi
[Unit]
Description=Your Service Description
After=network.target

[Service]
ExecStart=/path/to/your/script.sh
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

The [Unit] section describes the service and when it should start.

The [Service] section tells systemd what to run and how.

Examples
This example runs myscript.sh as user pi after the network is ready.
Raspberry Pi
[Unit]
Description=My Auto Start Script
After=network.target

[Service]
ExecStart=/home/pi/myscript.sh
Restart=always
User=pi

[Install]
WantedBy=multi-user.target
This runs a Python script once at boot without restarting if it stops.
Raspberry Pi
[Unit]
Description=Simple Hello Service
After=multi-user.target

[Service]
ExecStart=/usr/bin/python3 /home/pi/hello.py
Restart=no
User=pi

[Install]
WantedBy=multi-user.target
Sample Program

This is a full example of a systemd service file to auto-start a script called hello.sh located in the pi user's home folder. The comments show how to enable and start the service.

Raspberry Pi
[Unit]
Description=Auto Start Hello Script
After=network.target

[Service]
ExecStart=/home/pi/hello.sh
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

# Save this as /etc/systemd/system/hello.service
# Then run:
# sudo systemctl daemon-reload
# sudo systemctl enable hello.service
# sudo systemctl start hello.service
OutputSuccess
Important Notes

Make sure your script has execute permission: chmod +x /home/pi/hello.sh.

Use sudo systemctl status yourservice.service to check if your service is running.

Reload systemd after creating or changing service files with sudo systemctl daemon-reload.

Summary

systemd services help run programs automatically at boot on Raspberry Pi.

Create a service file with sections [Unit], [Service], and [Install].

Enable and start the service using systemctl commands.