UNIX – Start Service If Not Running

| | | |

Currently this script is developed for my Raspberry Pi (Debian, Raspbian) but in time I will have it working for RHEL (Red Hat, CentOS, Fedora).

service=openvpn
running=$(ps -ef | grep -v grep | grep $service | wc -l)
#echo $running
if [ "$running" = 1 ]; then
  echo "$service is running!!!";
else
  echo "Starting $service!!!";
  sudo /etc/init.d/$service start
fi

sudo netstat -uapn | grep openvpn

In the example above I’m checking if OpenVPN is running, if it is not running it will start the service.

I set this script up as CheckOpenVPN.sh in my /opt directory so I can simply run the below.

sudo sh /opt/CheckOpenVPN.sh
Originally Posted on February 2, 2018
Last Updated on June 18, 2019
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.