Shell Script to Restart the Services if Down/Crashed
It’s common for process to crash/go down due to various reasons, which you can investigate and fix the issues but that may take little time. However, one thing you can do it immediately to reduce the downtime for better availability is to automate restart of the process if it’s down.
Let’s get this done through the free way – shell scripts
You can use following shell scripts to run through crontab, which will check the services at every 5 minutes (you can adjust the interval time) and will start if found not running. Sounds cool?
Make the script steps:
1 – update-rc.d cron defaults
2 – /etc/init.d/cron start
3 – nano /opt/startifdown.sh
4 – copy the bash code below to your script file “startifdown.sh”
5 – crontab -e
6 – Add the code at bottom (note this cron will run every 5m)
*/5 * * * * /opt/startifdown.sh >/dev/null 2>&
7 – Be sure the scrip is executable: chmod +x /opt/startifdown.sh
The “startifdown.sh” file:
#!/bin/bash #Scripts to start services if not running ps -ef | grep nginx |grep -v grep > /dev/null if [ $? != 0 ] then /etc/init.d/nginx start > /dev/null fi ps -ef | grep php5-fpm |grep -v grep > /dev/null if [ $? != 0 ] then /etc/init.d/php5-fpm start > /dev/null fi ps -ef | grep mysql |grep -v grep > /dev/null if [ $? != 0 ] then /etc/init.d/mysql start > /dev/null fi
You can adjust the script to add other services such postfix dovecot and others, just remember to close the statement with “fi”.
Thank you for seeing my tutorial and fell free to share and comment 🙂 . Do you have a code snippet and you want to see it publish on my site ? I will be more than happy to do it please send me a message (here)