Script to check if a process is running and if not start it

Script to check if a process is running and if not start it

A pretty simple script that uses pidof to check if a process is running and if not restart it (Thanks go to weirdo for warning me about the perils of grepping ps output) :) The script does use systemctl by default but you can comment the section out to use service. This script is running on a Fedora 16 but it should work on pretty much any Linux with minimal changes

#!/bin/bash
# A simple script to check if a process is running and if not will
# restart the process and send a mail.
################################################
# The name of the program we want to check
PROGRAM=openvpn

# The user we would like notified of the restart
MAILUSER="someone@weeenospam.blah"
################################################

PROCESSPID=$(pidof -s $PROGRAM)
if [ -z "$PROCESSPID" ];
then
# Use systemctl
systemctl stop $PROGRAM.service
systemctl start $PROGRAM.service
# Comment above and uncomment below to use service rather than systemctl
# service $PROGRAM restart
echo mail -s "Service $PROGRAM was found to be stopped on $HOSTNAME at $(date) and has been restarted" $MAILUSER << /dev/null
echo "$PROGRAM had FAILED on $HOSTNAME @ $(date)" >> $PROGRAM-check.log
else
echo "$PROGRAM was running ok on $HOSTNAME @ $(date)" >> $PROGRAM-check.log
fi
exit

Then it simply a case of adding a cron job to run this script as often as you like. This cron entry will check the service is running every 10 minutes.

# Checking my service
 */10 * * * * /home/m00nie/checkmyservice.sh > /dev/null 2>&1

Job done
m00nie :D