How do I create a service for a shell script so I can start and stop it like a daemon?

If you'd like to reuse your code sample, it could look something like:

#!/bin/bash

case "$1" in 
start)
   /path/to/hit.sh &
   echo $!>/var/run/hit.pid
   ;;
stop)
   kill `cat /var/run/hit.pid`
   rm /var/run/hit.pid
   ;;
restart)
   $0 stop
   $0 start
   ;;
status)
   if [ -e /var/run/hit.pid ]; then
      echo hit.sh is running, pid=`cat /var/run/hit.pid`
   else
      echo hit.sh is NOT running
      exit 1
   fi
   ;;
*)
   echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0 

Naturally, the script you want to be executed as a service should go to e.g. /usr/local/bin/hit.sh, and the above code should go to /etc/init.d/hitservice.

For each runlevel which needs this service running, you will need to create a respective symlink. For example, a symlink named /etc/init.d/rc5.d/S99hitservice will start the service for runlevel 5. Of course, you can still start and stop it manually via service hitservice start/service hitservice stop


I believe CentOS 7 and above uses systemd. If that is the case for your system, try the following:

  1. Place the script commands you wish to run in /usr/bin/myscript.

  2. Remember to make the script executable with chmod +x.

  3. Create the following file:

/etc/systemd/system/my.service

[Unit]
Description=My Script

[Service]
Type=forking
ExecStart=/usr/bin/myscript

[Install]
WantedBy=multi-user.target
  1. Reload all systemd service files: systemctl daemon-reload

  2. Check that it is working by starting the service with systemctl start my.

Bonus:

For testing the systemd service, it is possible to launch a tmux environment with two window panes, where the top window monitors the output from the script (stdout and stderr) and the bottom window can be used for restarting services. This requires tmux to be installed, then simply:

tmux new-session \; select-layout even-horizontal \; split-window -v journalctl -o cat --since=@$(date +%s) -f -u my \; rotate-window \; set -g status-bg colour0 \; set -g status-fg colour9 \; attach

Then restart the service with:

systemctl restart my

Exit tmux with ctrl-d and then ctrl-c.


This is my script as a service:

[Unit]
Description=To change In test buffer
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/test.sh
TimeoutStartSec=0

[Install]
WantedBy=default.target