WriteBash - 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.
root@debian9:~# wget https://gitlab.com/Danny_Pham/WriteBash.com/raw/master/Utilities/04-Script%20get%20server%20load%20information.sh -O /opt/getload.sh
Then, you need to set permission
700 for this script.
root@debian9:~# 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
root@debian9:~# nano /etc/systemd/system/getload.service
Then, you copy the content below to file
[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.target
You 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.
root@debian9:~# systemctl enable getload
Recommended 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 found
Type the following command to solve that error.
root@debian9:~# apt-get install systemd -y
And now, we use this command check the getload service works.
root@debian9:~# systemctl start getload && systemctl status getload
The article hopes that you can create the service file in Debian 9, which can make your bash script file run as a service.If you liked this article, then please subscribe to our YouTube Channel for more video tutorials. You can also find us on Twitter and Facebook.
If you appreciate what we share in this blog, you can support us by:
- Stay connected to: Facebook | Twitter | Google Plus | YouTube
- Subscribe email to recieve new posts from us: Sign up now.
- Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
- Become a Supporter - Make a contribution via PayPal.
- Support us by purchasing Ribbon Lite Child theme being using on this website.
We are thankful for your support.