How to Create Service Files with Systemd « Null Byte :: WonderHowTo

We will discuss a basic example on how to execute shell script during a boot time on systemd Linux. There may be various reasons why you might want to execute shell script during Linux startup-like for example to start a particular custom service, check disk space, create a backup, etc. In this post, we are going to discuss Run a script as a Service.

assume that we have a script called, test.sh . we are going to Run this script as a Service. first of all lets make this script executable:

$ chmod a+x test.sh

let’s create a config file called test.service. we have to place this script in /etc/systemd/system/

[Unit] Description=test service
After=network.target
After=systemd-user-sessions.service
After=network-online.target
[Service]
User=spark
Type=forking
ExecStart=/pathto/test.sh
ExecStop=/pathto/test.sh
TimeoutSec=30
Restart=on-failure
RestartSec=30
StartLimitInterval=350
StartLimitBurst=10
[Install] WantedBy=multi-user.target

To setup the service:

$ sudo systemctl start test.service
$ sudo systemctl stop test.service

Enabling and Disabling Services

The above commands are useful for starting or stopping commands during the current session. To tell systemd to start services automatically at boot, you must enable them.
To start a service at boot, use the enable command:

$ sudo systemctl enable test.service

This will create a symbolic link from the system’s copy of the service file into the location on disk where systemd looks for autostart files.

To disable the service from starting automatically, you can type:

$ sudo systemctl disable test.service

This will remove the symbolic link that indicated that the service should be started automatically.

Keep in mind that enabling a service does not start it in the current session. If you wish to start the service and enable it at boot, you will have to issue both the start and enable commands.