Bash Script: Check service and auto start if needed


If you are running a service and for some reason the service gets broken, you will want it to automatically restart. For that reason, I have created a script as below. Feel free to amend the array autoservice as needed because in my case it is monitoring mysqld, cherokee and squid.

#!/bin/bash
#Add values to the array autoservice seperated by spaces
autoservice=(mysqld cherokee squid)

#the code
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
for i in “${autoservice[@]}”
do
:
service $i status # > /dev/null
if [ $? -eq 0 ]; then
echo $i “Running..”
else
service $i restart
fi
done

Created in /scripts/checkService.sh, you need to chmod 777 the file and add it to crontab to run every 5minutes via the following:

 

chmod 777 /scripts/checkService.sh

 

crontab -e

add this line to run it every 5 mintues

*/5     *       *       *       *       sh /scripts/checkService.sh

Gulshan Yashveer Beejan

Gulshan holds a BSc(Hons) Computer Science with Distributed systems from the City University of London. He is currently working at DSOGroup(Mauritius) as a Linux Administrator on SaaS Solutions. More about Gulshan

One thought on “Bash Script: Check service and auto start if needed

  1. Pingback: Gulshan Beejan

Leave a Reply

Your email address will not be published. Required fields are marked *