HostOnNet Blog

Bash Script to restart stopped service

Looking for Linux Server Admin or WordPress Expert? We can help.

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 monitor-service.sh with following content.

#!/bin/bash

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

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

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/monitor-service.sh

Posted in Linux

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.