Table of Contents
This article will show you how to make a bash script run as a service in Debian 9. Debian is one of the most popular OSs in the world today.
Write your bash script
The first thing, of course, is that you need your bash script file. In fact, the script written in bash or another language doesn’t matter, it can be written in Perl, Python, and so on.
I wrote a demo script for this job, you download it from this link or you can write your own. You can use the following command.
wget https://gitlab.com/Danny_Pham/WriteBash.com/raw/master/Utilities/04-Script%20get%20server%20load%20information.sh -O /opt/getload.shThen, you need to set permission 700 for this script.
chmod 700 /opt/getload.sh
Recommended Reading: Make bash script run as a service on Ubuntu 16
Create service file for this script
The new Linux OSs are using the systemd structure, which makes it convenient for users to switch from one OS to another.
You type the command below to create the service file for the getload.sh script, this file you put it in the directory /etc/systemd/system/.
nano /etc/systemd/system/getload.serviceThen, you copy the content below to file getload.service.
[Unit]
Description=Getload service - WriteBash demo service in Debian 9.x
After=network.target
[Service]
Type=simple
PIDFile=/var/run/getload.pid
ExecStart=/bin/sh -c "/opt/getload.sh >>/var/log/getload.log 2>&1"
TimeoutStartSec=0
Restart=on-failure
[Install]
WantedBy=default.targetYou can set up logrotate for the log file /var/log/getload.log that we have declared in the file service.
Enable and start service in Debian 9
After everything above has been completed, we will now type the following command to enable service getload, enabling the auto start service when the server reboots.
systemctl enable getloadRecommended Reading: Make bash script run as a service on Debian 8
If you encounter the following error, it may happen if you use Docker for example, or for some reason.
bash: systemctl: command not foundType the following command to solve that error.
apt-get install systemd -yAnd now, we use this command check the getload service works.
systemctl start getload && systemctl status getloadConclusion
The article hopes that you can create the service file in Debian 9, which can make your bash script file run as a service.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).