HostOnNet Blog

Bash Script to restart stopped service

Here is a quick bash script that will monitor if a process is running. If not restart it. It only work if process completely crashed. If process hangs, it won’t help.

Create file with following content.


ps aux | grep nginx | grep -v grep > /dev/null

if [ $? -ne 0 ]; then
    service nginx restart

The code look for process with name nginx, if not found, restart service nginx.

You can replace nginx with whatever service you want to use.

Setting up Cronjob

You need run the above script every X minute to see if service is running, if not it will restart the service. This can be done by setting up a cronjob.

crontab -e

To run the script every 5 minutes, add

*/5 * * * * /path/to/

Posted in Linux