Run a startup script using systemd

Since most major Linux distros are now using systemd as their init system, perhaps it makes sense to learn how it works. Nevertheless, reading its full documentation, might feel a little bit daunting. So, if everything you need is to run a simple startup script when you boot into Linux, there's no need to become an expert in system. Instead, I'll guide you through a quick 3 step process:

1. Create your startup script

2. Create a unit file

3. Enable unit file in systemd

The first step is to actually create your startup script. You can place it anywhere, but a nice standard directory for user scripts is /usr/local/sbin. I'll call my script and as an example I'll use it to run hdparm to spin-down my HDD because I'm simply using it to backup data and therefore it's probably a good idea to save power and keep it quiet. Since we need to execute this file, let's make it executable with:

gluon@helium:~$ sudo chmod +x /usr/local/sbin/

Step two is to create a barebones systemd unit file. Unit files are stored under /etc/systemd/system and come in different flavours, but perhaps the simplest one is a service unit, so that's what we'll be creating here. I'll call it my-startup.service, because systemd differentiates unit types by file extension. Make sure you add these lines to your my-startup.service:

Description=My Startup



As you can see, there are are only three sections, Unit, Service and Install. The first section, Unit, has a single directive called description, which is basically what it says, a short description about your unit file, in this case "My Startup". Then, since this is a service unit, there must be a service section, also with a single directive called ExecStart. This tells systemd that when your unit is executed/started, it should run whatever script you place here. In this case, the path to the startup script we've created earlier.

Finally, we declare an Install section with a directive called WantedBy. What this means is that our unit is wanted by the multi-user target. In other words, the multi-user target depends on your service unit. systemd targets are similar to runlevels in classic init systems. The multi-user target, or runlevel if you will, is reached when your computer finishes booting and rigth before it launches the graphical user interface, in case you have one installed. Once the system reaches the multi-user target, it executes the corresponding dependencies of this target, which means our unit will be executed and therefore our startup script ( will run, which is exactly what we want.

The last step is to enable your recently created unit file in systemd using the systemctl command:

gluon@helium:~$ sudo systemctl enable my-startup.service
Created symlink /etc/systemd/system/ → /etc/systemd/system/my-startup.service.