A very basic SystemD service

Sometimes I find myself trying to execute something at boot, or have it run daily, or after the system has been running for some time.

For that, most Linux distros have the SystemD daemon management system, and this is how to make a very simple service file

We are going to create a text file in /etc/systemd/system/ and add the following

[Unit]
After=multi-user.target

[Service]
ExecStart=/usr/bin/bash -c /root/.scripts/service.sh
Type=exec
Restart=on-failure

[Install]
WantedBy=default.target

What are those lines?

After=multi-user.target
This means that it's going to run after everything else is loaded, and should be what most programs need.

ExecStart=/usr/bin/bash -c /root/.scripts/service.sh
You might notice that we are executing a shell script in root's home folder, that it's the most simple way to run multiple commands in succesion, otherwise we can only run just one thing per service.

Type=exec
The exec type is what most programs need, it waits untill the command is fully running for it to be considered, well, running.

Restart=on-failure
This makes it restart when it exits with a non-zero code, unclean signal, a timeout, or watchdog failure.

WantedBy=default.target
Finally, this means that it should load because the default target wants it, and should ideally start before it.


Finishing

After that we only have to run

sudo systemctl enable name.service

and it should run on next boot, however if we want to have it run right now we can add —now after enable, or simple run it again but with start rather than enable.