Shell Script To Auto Restart Apache HTTPD When it Goes Down / Dead

in Categories HTTP, Web Server last updated July 22, 2008

Here is a simple shell script tested on CentOS / RHEL / Fedora / Debian / Ubuntu Linux. Should work under any other UNIX liker operating system. It will check for httpd pid using pgrep command

pgrep command

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to screen. If no process found it will simply return exit status 0 (zero).

Download the script and set cronjob as follows:
*/5 * * * * /path/to/ >/dev/null 2>&1

Sample script

A better and more reliable solution is monit monitoring software for restarting services such as mysql, apache and sendmail under UNIX / Linux operating systems.

Share this on:

27 comment

  1. I am not a big fan of greping httpd in process list to see if httpd server is running or not. There can be several httpd services installed. Two options are either the status module, or this bash script to the extent that you known the full path to your httpd bin folder:

    function isapup(){
    pid=$($1/bin/apachectl -S | grep PidFile | awk ‘{print $2}’) # retrieve the expected path of the process id file
    pid=${pid:1:expr ${#pid} - 2} # get rid of the quotes
    up=$(ls $pid 2> /dev/null) # see if process id file exists

    if [ ! “$up” ]
    return 1

    isapup /opt/httpd/2.4.0

    if [ $? -eq 1 ] # if isapup returned 1
    echo Starting Apache
    /opt/httpd/2.4.0/bin/apachectl start

  2. If adapting this for other processes add an -x flag to force pgrep to match the process name exactly


    The name of my script contains the name of the the process to pgrep was giving a false positive when the process wasn’t running.

  3. You made mistake in crontab entry. It will not work.

    You should specify user which will execute the script:

    This crontab is correct (CentOS):

    */5 * * * * root /path/to/ >/dev/null 2>&1

    Have a question? Post it on our forum!