Write a Service Unit on Arch Linux

A service unit describes how to manage a service or application. This includes how to start or stop the service, under which circumstances it should be automatically started, and the dependency and ordering information for related software.

System Unit files are generally loaded from:
/etc/systemd/system/

Below is an example of a simple service unit file:

Using this example you can automate certain tasks on boot. You just need to change the service dependency and the script that you need to execute.

[subhankd@archm system]$ cat /etc/systemd/system/my_sub.service
[Unit]
Description=My Service -- Run before sddm
Before=sddm.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/my_sub.sh
ExecStop=/usr/local/bin/my_sub2.sh

[Install]
WantedBy=sddm.service

[Unit] Section

The first section found in most unit files is the [Unit] section. This is generally used for defining metadata for the unit and configuring the relationship of the unit to other units.

  • Description= : Set this to something short, specific, and informative.
  • Before=sddm.service : Here I have used the sddm service as my trigger. sddm is the display manager that was installed on my machine.

[Service] Section

The [Service] section is used to provide configuration that is only applicable for services.

  • Type=oneshot: This is useful for scripts that do a single job and then exit.
  • RemainAfterExit=yes : So that systemd still considers the service as active after the process has exited.
  • ExecStart=/usr/local/bin/my_sub.sh : Execute the script before starting sddm.
  • ExecStop=/usr/local/bin/my_sub2.sh : Execute the script before stopping sddm.

[Install] Section

This section is optional and is used to define the behavior or a unit if it is enabled or disabled. Enabling a unit marks it to be automatically started at boot. This is accomplished by latching the created unit in onto another unit that will be started at boot.

  • WantedBy= : To specify how a unit should be enabled. This directive allows you to specify a dependency relationship

Now once you have the service unit file ready, create the script file as per your requirement. Do make sure the script files are executable by the root user.

Finally enable the service you just created, to start at boot:

[subhankd@archm system]$ systemctl enable my_sub.service

Leave a comment

Design a site like this with WordPress.com
Get started