How to Run a Script as a Service in Linux Distro in Reliable way

      Comments Off on How to Run a Script as a Service in Linux Distro in Reliable way

Linux administrators mostly face some cases where they need to run a script as a service. This includes some custom monitoring scripts to trigger some failover jobs.

Here we see how we can run a script as a service in the centos server.

[[email protected] ~]# vim /opt/
[[email protected] ~]# cat /opt/ 
while true; do
    echo "Hello world" > /var/log/helloworld.log
    sleep 60s
[[email protected] ~]#

To run this script as a service, all we need to do is create a systemd service file under /etc/systemd/system/ directory,

[[email protected] ~]# vim /etc/systemd/system/helloworld.service
[[email protected] ~]#
[[email protected] ~]# cat /etc/systemd/system/helloworld.service
Description=Hello World

ExecStart=/bin/bash /opt/
ExecReload=/bin/kill -HUP $MAINPID

[[email protected] ~]#

Once you saved this file your script can be started as a service. You can just start it as a normal service.

You can even enable this service to run in boot time,

[[email protected] ~]# systemctl enable helloworld.service
Created symlink from /etc/systemd/system/ to /etc/systemd/system/helloworld.service.
[[email protected] ~]# 
[[email protected] ~]# systemctl is-enabled helloworld.service
[[email protected] ~]# 

That’s It. Now our script is running a service.

Also, we can use setsid command to run a script as a service,

SETSID Example:

setsid /opt/ >/var/log/helloworld.log 2>&1 < /dev/null &

But systems service file is the best way to do this. Which way you prefer, leave your comments below.

Sharing is caring!


I'm an IT professional having multiple years of experience in IT Infrastructure planning, System integrations, Project implementation, and delivery. DevOps Enthusiast skilled with broad ranges of technology adoption. Well versed with Cloud Computing and Application Service Offerings such as SaaS/PaaS/IaaS. Expert in aligning business goals, mission and process to architect innovative solutions and strategies.