Mostly major distributions, such as Rhel, CentOS, Ubuntu, Fedora, Debian etc, adopted systemd as its init system. systemd uses its own .service files (units with the .service suffix), whereas other init systems use simple shell script to manage services. In this tutorial we will see how services are structured and how to create a systemd service unit for shell scripts in linux.
Systemd service file contains .service (extension) suffix contains information about a process. It is consists of three sections:
- [Unit]: this section contains information about the service description.
- [Service]: In this section, we can provide specific type of the unit information.
- [Install]: This section contains information about the installation of the unit.
We need to create our service under below path.
# cd /etc/systemd/system
Let’s have a look on syntax of systemd service unit.
[Unit] Description=creating a demo service After=Network.target [Service] ExecStart = /root/scripts/sample.sh [Install] WantedBy=multi-user.target
Here we have to provide some details regarding owner of the service and start or stop script path etc.
# cd /etc/systemd/system # vim test.service
[Unit] Description=Test Service After=network.target [Service] Type=forking User=#username WorkingDirectory=<directory_of_script e.g. /root> ExecStart=<script which needs to be executed> Restart=always [Install] WantedBy=multi-user.target
After creating the service, we must reload the service files to include in new service list.
# sudo systemctl daemon-reload
Next start your service.
# sudo systemctl start test.service
Status of the newly created service can be checked by below command.
# sudo systemctl status test.service
If this service is very critical and we want to make sure this service should run after reboots of the server, then we should enable this service with the below command.
# sudo systemctl enable test.service
This service can be stopped and disabled with the below command if you do not want to service any more.
# sudo systemctl stop test.service # sudo systemctl disable test.service
Hence we just learned how to create a systemd service unit for Shell Scripts in Linux.
I hope this works.
Read More: How to install Terraform on Ubuntu 20.04