Table of Contents
How to make a bash script run as a service in Ubuntu 16. This tutorial will guide you to do that. In my blog I have written the same topic for CentOS 7. Ubuntu 16 and CentOS 7 use systemd, you can see the similarity in these two posts.
Write your bash script
You can read the article below, I will reuse the script getload.sh in that article. The purpose of the script is to collect server load information once a second, write the information to a text file and include the timestamp.
You can download the script here.
How to make bash script run as a service in CentOS 6
In fact, this method can be used for any type of script, bash script, python, etc. You remember that you need to grant the permission 700 for your script.
Make bash script run as a service
As in the article for CentOS 7, both Ubuntu 16 and CentOS 7 use systemd, so you can apply this for both operating systems.
How to make bash script run as a service in CentOS 7
Create a service file
You create a new file named/etc/systemd/system/getload.service and copy the following content into that file.
[Unit]
Description=Getload service - WriteBash demo service in Ubuntu 16.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.targetAbove, you can edit the following information to match the service you want to create (Part of this information, as mentioned in the article link for CentOS 7 above.):
- Description: describe your program.
- PIDFile: the path to the PID file you want.
- ExecStart: the command to execute the program, here we call the main script mentioned above the article.
Create logrotate file for service
You can see the “Create logrotate file for service” section in the article link for CentOS 6 at the beginning of this article.
This part is quite simple.
Check the result
To enable your service after reboot, you run the command:
systemctl enable getloadTo start/stop/check status of your service, run command below:
systemctl [start|stop|status] getloadAnd you can see the results in the image below.

Conclusion
If you have read the article on how to make bash scripts run as a service on CentOS 7 then you are familiar and not having any trouble doing it on Ubuntu 16. However, anyway, CentOS 7 and Ubuntu 16 are also two different operating systems, I still want to test and write a separate article for each operating system.
(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).