Bash script to check if a service is running


In production sites, we normally need to ensure that everything must go fine. However, in many cases, some server services are terminated which causes your website broken/died. For example, sometimes hhvm goes down in my production server which cause my commercial system stop working. This is hurt and it affects directly to my pocket :-(. So, I must think a way to monitor a service periodly and restart it if it is broken. In this short tutorial, I will guide how to write a bash script to check if a service is running.

First, create the following bash script, name it script_check_hhvm.sh for example:

[bash]logfile="/var/log/hhvmcheck.log"

case "$(pidof hhvm | wc -w)" in

0) echo "hhvm not running, restarting oscam1: $(date)" >> $logfile
service hhvm start
;;
1)
;;
*) echo "multiple instances of hhvm running. Stopping & restarting hhvm: $(date)" >> $logfile
service hhvm restart
;;
esac[/bash]

In the above script, if hhvm is stopped, there is no hhvm process and we will start it by service hhvm start command. When there is more than 1 hhvm process, it means that there is some problem in our system and we will restart it.
Then, setup it as a cron run every 2 minutes via crontab:

[bash]crontab -e
*/2 * * * * sh /root/script_check_hhvm.sh[/bash]

It’s all! You can easily replace the command actions for your cases with the above script and enjoy it 🙂


About NhocConan

A super lazy guy who tries to write tech blog entries in English.He is lazy, so he can only write when he is in a good mood or when he is tired of coding.

Leave a comment

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