linux script to check if a service is running and start it, if it’s stopped

Here is a simple script that will check if your specified service is running and will start it if it’s stopped.

You will have to replace “replace_me_with_a_valid_service” with the name of the service you want to check

#!/bin/bash
service=replace_me_with_a_valid_service

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
echo "$service is running!!!"
else
/etc/init.d/$service start
fi

You can place it in crontab and have it executed automatically
eg. to check every minute, insert into cron

* * * * * /path/to/script
Leave a comment ?

103 Comments.

  1. Manjunath Mariyappa

    Hi there,

    Thank you very much for posting this neat and perfectly working shell script.
    I have tested the shell script and found it to be working fine.
    once the service is restarted the script should me modified so that the service is again grepped and a mail is sent to the concerned administrator.

    • I’m glad you found it useful

      Here is the script modified to suit your needs. You must have mailx installed, for installation check my post here.

      #!/bin/bash
      
      ###edit the following
      service=service_name
      email=user@domain.com
      ###stop editing
      
      host=`hostname -f`
      if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
      then
      echo "$service is running"
      else
      /etc/init.d/$service start
      if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
      then
      subject="$service at $host has been started"
      echo "$service at $host wasn't running and has been started" | mail -s "$subject" $email
      else
      subject="$service at $host is not running"
      echo "$service at $host is stopped and cannot be started!!!" | mail -s "$subject" $email
      fi
      fi
      
      • For me it is not working, it says httpd is running even if it is stopped. here is my code
        #!/bin/bash

        ###edit the following
        service=httpd
        email=vibhu@arackal.in
        ###stop editing

        host=`hostname -f`
        if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
        then
        echo “$service is running”
        else
        /etc/init.d/$service start
        if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
        then
        subject=”$service at $host has been started”
        echo “$service at $host wasn’t running and has been started” | mail -s “$subject” $email
        else
        subject=”$service at $host is not running”
        echo “$service at $host is stopped and cannot be started!!!” | mail -s “$subject” $email
        fi
        fi

        The output of ps -ef | grep -v grep | grep $service | wc -l is showing 0, still it is entering the true section. I am using Amazon Linux AMI. Can u help me in this? I want to check frequently my httpd service is running or not and if it is not running I must get a mail stating that and run the service automatically

        • Hi vibhu

          whats the output from

          ps -ef | grep -v grep | grep httpd | wc -l
          • the output of ps -ef | grep -v grep | grep httpd | wc -l is showing 0. I have mentioned it in my previous post 😉

          • what kind of linux distro are you using?

            when apache is stopped and you execute the script from the console, you get the following message?

            httpd is running

            what’s the output from

            ps -ef | grep -v grep | grep apache2 | wc -l
          • Linux version : Linux version 3.2.30-49.59.amzn1.i686 (mockbuild@gobi-build-31003) (gcc version 4.4.6 20110731 (Red Hat 4.4.6-3) (GCC) ) #1 SMP Wed Oct 3 19:55:00 UTC 2012

            Yes when httpd is stopped i get the message: httpd is running

            ps -ef | grep -v grep | grep apache2 | wc -l returns 0

            I hav attached a screen shot of the same to user@domain.com for your reference.

          • Try executing the commands as root.
            Also execute with bash not with sh

            run

            ps -ef > akamaras.txt

            and email me akamaras.txt (you’ll find it in the directory you executed the command)

            You can send it from the console, using the following command (replace user@domain with my email)

            mail -s ‘Vibhu’ user@domain.com < akamaras.txt
          • Executed the commands with root; executed the script using bash; still no result,
            Mailed you ‘akamaras.txt’ file.
            I think the IF condition is not working properly, is there any problem in the script?

        • I know this is an old thread but I found this, I got the same results as vibhu, script says service is running when it is not.
          The service I am checking is minecraft and my script was named check_minecraft_service.
          I ran “ps -ef | grep -v grep | grep $service” on top of the script to se what it returned and in the results was my script. So I renamed the script to “check_mc_service” and then the script worked.
          So somehow the script name is included in the grep and therefore the service is listed as running.

        • This is old thread, but the problem is value of $(ps -ef | grep -v grep | grep $service | wc -l) is different beetwen terminal and bash script.

          So to fix this, please assign like this:
          data=$(ps -ef | grep -v grep | grep $service | wc -l)

          and then, echo $data to know the real value of those.

          I found, when service start value is 5, and service off value is 2.

          By using if else (value>0) the return value is always TRUE..

          so you can fix with new if else with real return value from bash script not from terminal.

      • if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )) after /etc/init.d/$service start does not work as grep $service will return nothing

        Reason : ps does not show the name of child process in it’s output. Instead it will show parent process’s name which would be the script that runs all the above code.

        ex :
        cat abc.sh
        . def.sh
        EOF

        cat def.sh
        echo test
        sleep 20
        EOF

        Now, on executing abc.sh, ps will show abc.sh and not def.sh( which has been called from inside abc.sh) under its CMD attribute. So, grep def won’t return anything.

        I am stuck here.

  2. Manjunath Mariyappa

    Thanks for the modifications. This has fulfilled my requirements.

    • Kasaija Ronald

      Hi Manjunath, I’m having the same problem that you were having. How did you solve it? Thanks

    • command
      —————-
      ps -ef | grep -v grep | grep apache2 | wc -l

      Output : 1

      above command will return 1 if apache2 service is running.
      if there is not apache2 service it will retrun 0

  3. Is that service running? « 0ddn1x: tricks with *nix - pingback on 16/10/2012 at 19:46
  4. Vikram Keswani

    Dear Akamars,

    Hope that you are having a good time.

    On linux base application server, How can I make a script to check the file size, if it is not increasing then RESTART SERVICE and system check this after each 10 minutes.

    Regards
    Vikram Keswani

    • Hi Vikram

      You want to check the size of a file?

      A quick solution would be the following. There may be better ways…

      • Echo the size of the file you want to check, to a file(lets name this file oldvalue.txt)
      • Next time the script gets executed it will compare the current size with the one that oldvalue.txt has
      • If the size is bigger, just echo the current size to oldvalue.txt overwriting the previous value
      • If the size is equal or smaller to the one oldvalue.txt has, restart the service

      As for the 10 minutes interval cron is your friend

  5. Hi, I ran the script you have in ubuntu

    ###################

    #!/bin/bash
    service=blah

    if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
    then
    echo “$service is running!!!”
    else
    /etc/init.d/$service start
    fi
    ###################

    The problem is that it is still showing the service as started even though it is still runnning.

    service blah start [ok]

    can youplease tell me if i am missing something here.

  6. why not use $1 for the service name and you can use this script any time with any service

    • Yes, you’re right the script would be more flexible using $1. At the time I wrote it, that’s what I needed. If you have the time, it would be great if you could explain to people reading, what should they change to use it with $1 and why it is better.

      Cheers

  7. SKVENKATES

    Thanks alot!!!

  8. it didnt worked for me — stupid mistake:
    i named the script “restart-myservice.sh” to restart the service “myservice”…

  9. I am needing to restart mysql with this and every time I invoke the script using a line inserted into the sudo crontab, it returns “initctl: not found” and “start: not found” when it attempts to start up the service. If I try to start it up from a shell directly by doing “sudo /etc/init.d/mysql start” it works. Do you have any insight on this?

    • try running the script from roots cron without sudo

      • I believe I did just that, as I do not have “sudo” in the script anywhere, but it still does not work.

        Here is the script I am attempting to use:

        ——————————————-

        #!/bin/bash
        service=mysql

        if ( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )
        then
        echo “$service is running!!!”
        else
        /etc/init.d/$service start
        fi

        ——————————————

        It never starts the service, the logs repeatedly show: “/etc/init.d/mysql: initctl: not found” and “/etc/init.d/mysql: start: not found”

        Thanks for your assistance

        • I discovered how to get the script to start the mysql service, I had to define PATH in line 2 of the script.

          Now my issue is this:

          When using the line “if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))”, the service is detected as running even when it is not.

          Then I tried the line “if ( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )”, the service is detected as NOT running even when it is.

          Is there an alternate method for checking if the service is running? The strange thing is that, if I run “ps -ef | grep -v grep | grep mysql | wc -l” from a terminal when the service is stopped, it returns ‘0’, but in the context of the script, it always prints “mysql is running!!!”

          • hi chandler, i am also getting same error.can please tell me how to start the service from script.
            my script is:
            #!/bin/bash
            service=zipgateway

            if ( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )
            then
            echo “$service is running!!!”
            else
            /etc/init.d/$service start
            fi

            showing the log as:/etc/init.d/zipgateway: not found

      • Sorry for the spam, I figured it all out.

        I was using the $service variable for both trying to check the process list for the service and also to start it. However, MySQL appears in ps as “mysqld” but it has to be started with “mysql,” so I just did away with the variable and all works now.

        Thank you for putting this script out there!

  10. Mysql on RaspberryPI (ARM debian)
    I don’t know why but it works with

    if ([ $(ps -ef | grep -v grep | grep $service | wc -l) > 2 ])

    instead of:

    if ([ $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ])

    • Hi I tried to replace it with 2 and it worked..Not sure why
      ps -ef | grep -v grep | grep processname | wc -l is giving 0 in console ..but in if case it is giving 2 when process is not running

  11. Hello,

    Have a look at:

    https://github.com/surfingtux/natty/blob/master/chkservices.sh

    You can use and improve you script.

  12. This wont work if any other process name username or executable script has the service name in it.

    A fix would be to have 2 variables
    servicex=’/usr/bin/foo’
    service=’foo’
    For the grep use servicex
    if (( $(ps -ef | grep -v grep | grep $servicex | wc -l) > 0 ))

    Then grep will filter by the specific executable path which is more reliable.
    .
    Additionally increasing the > 0 is a possible solution but unreliable since if another process is running with the service in the name will show the service is running even if it’s not.

    This is more of a quick short term solution for a temporary issue. If you need constant monitoring as a long term solution look for actual software that does this.

  13. also you could use awk to only list the specific column from the ps-ef

    ps -ef | awk ‘{ print $8 }’ | grep $service | wc -l

    still wont work if another application has the same word as your service in it though. Explicit executable path is probably best.

  14. Hi,

    This script not working for me. I had a problem with Idera Backup software because their agent dies everytime when they upgrade (reported to Idera few months ago – without any result) it and I try this script but it’s not working for it.

    If I run “ps -ef | grep -v grep | grep httpd | wc -l” in cli the result is “0” when the “service cdp-agent status” returns me: “/etc/init.d/cdp-agent status: cdp (pid 17039) running”. When the script is stopped then result is the same from this check.

    My server using CentOS 6.5, if anyone can help i’ll be very grateful 🙂

    Best regards,
    George!

    • Hi Georgi

      Try replacing “service=replace_me_with_a_valid_service” with “service=agent” at the second line of the script.
      What is the output of the following command?

      ps -ef | grep -v grep | grep agent | wc -l
  15. Need advise. I am new to Linux but I need to have a cron job executed when one of the app services (orbadmin ns) is down to start it up but with one condition it should restart – when other services are running. We don’t want to have that service restarted when app is brought down for maintenance

    • Hi itreyger,

      You could try the following script and let me know if it suits you. I haven’t tried it, I wrote this on the move on a text editor, so if it’s not working, let me know and I will fix it.

      #!/bin/bash
      
      service=replace_me_with_orbadmin
      secservice=replace_me_with_another_service_that needs_to_be_running
      
      if (( $(ps -ef | grep -v grep | grep $secservice | wc -l) > 0 ))
      	then
      		echo "$secservice is running!!!"
      	else
      		if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
      				then
      				echo "$service is running!!!"
      					else
      					/etc/init.d/$service start
      		fi
      fi
      
  16. Hi,

    Need small help on the below testcase.

    I have an input file with the below details separated by “,”
    component name,databasename,username,password details and I need to update those details in config file which are under different sub directories after matching with component name and db username.

    Please help me on this testcase.

  17. Snehal Patel

    I am new to Linux technology and I want to workout for my web server issue.

    Some time httpd ad mysqld service is not responding then we have to restart service manually.

    Can you please help me in this case.

    • Hi Snehal,

      Have you tried to use the script?
      Were there any problems?

      • Thanks for prompt reply.

        I have tried script and received syntax error as below.

        wc” invalid option –1
        try “wc –help” for more information.
        ./MySQL-autorestart.sh: line 4: ((: > 0 : syntax error: operand expected (error token is “> 0 “)

        service is starting but not responding for 2 or 3 minutes then it responding.

        I want to auto restart mysqld and httpd both. I would also like to restart whole server once in day.

        Can you please suggest?

        • ===================
          #!/bin/bash
          service=httpd

          if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
          then
          echo “$service is running!!!”
          else
          /etc/init.d/$service start
          ===================

          create another script for Mysqld

          ===================
          #!/bin/bash
          service=mysqld

          if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
          then
          echo “$service is running!!!”
          else
          /etc/init.d/$service start
          ===================

        • The error says that you have 1 (number one) instead of l (lower case L letter). Just copy and paste my script changing only the second line(name of the service).

  18. Hi

    I am using centos6.5 and tried running your script from the cronjob to start the stopped service. But from the cronjob it does not work but if I execute the script directly it works fine.
    Can you get me some insight what might be wrong?

    Thanks
    Hamid

    • issue the following command

      chmod +x script_name

      and then check if it’s working from cron

      • Executable permission is already set.

        Permissions are as below:
        -rwxr-xr-x test-char.sh

        And the cronjob is as below:
        */1 * * * * /tmp/test-char.sh

        Does not work from Cron?
        Basically from cron it can’t execute “service servicename start|stop|status”

        Even tried with /sbin/service or /etc/init.d/servicename but still the same result.
        Any other advise on this?
        Thanks

  19. How can i check if the service is present but not responding or Freeze..? what can be the script like?

  20. Hi Akamaras
    If i have multiple services running on a single host.what would be the script to get notify by mail if any of the services are stopped on that host.

    • Hi naga

      You can create a file and put there the services you want to check.
      Then you can put the code from my script in a loop where each service will be checked one after the other.
      Unfortunately I don’t have time at the moment to write the script for you but if you follow my instructions and try to find some examples on the internet you shouldn’t have a problem writing it yourself.

  21. Thanks Akamaras.I am newbie to unix.anyways i’ll try my luck.

  22. please help!!!!!!!!!!!

    Writer a shell script to capture the services logs……..
    Like:- if there is a service(httpd), i need to capture the start, stop and restart tilme and details

    • If you have the script executed using cron, you could direct the output to a file.

      For example you could have something like the following in cron

      * * * * * /path/to/script >> /path/to/logfile
      
  23. Hi every one

    i want to monitor apache2 mysql nodejs mongodb services with shell script please give me the script for this..thank you

    • Hi venu.

      You could create a file containing the list of the services you want to monitor and put the code of the script inside a loop.
      Each time the loop, loops the “service” variable will be replaced with the next service.

      Eg.

      while read service; do
      
      PLACE THE CODE OF THE SCRIPT HERE
      
      done < filename.txt
      
  24. One of the server is shutting down automatically, So how can I modify the script to check the server status and if the server is going to shut down the script should start the server again.

    • You can’t have a script to start the server in case it shuts down. The script needs the operating system in order to be executed, if the server is down the operating system is down as well.
      I suggest to investigate and find the reason why your server is shutting down and fix it.

  25. Hi,

    How do I update this script to get all the services on the server.

    I’m running it on RHEL 6

    • I think your best bet would be to use one of the modifications above.

      Get rid of the “service=replace_me_with_a_valid_service” line, and replace $service with $1 everywhere in the script. Then, save it as e.g. check_service.sh and call it for each service you want to check.

      /path/to/check_service.sh apache2
      /path/to/check_service.sh mysqld
      etc.

      Use a second script to run through a list of the services you want to check and run check_service.sh. What that list is will be up to you. Listing files in /etc/init.d/ probably won’t work, nor will using “service –status-all” because you’ll get a lot of stuff that shouldn’t be running at all times.

  26. Sharad singh

    Hello Everyone <

    I am new in Linux
    Is anyone help me to write an script as we are checking logs
    using ls -ltrh | tail
    and if any logs dosent contain traffics and we have to restart
    then i want to write an script which would help that it should check logs after every 1o min and if traffic would not come it automatically generte an mail to my mail box

    for mor help i need anyone's whatsapp no. please share your number to me my whats app no. iis 7080359116

  27. Hello there;
    How to make,
    install the war file, if alfresco and tomcat are running

  28. Six years old and still found! Good script! I made some small changes to remove some duplication, and also make it work with qmail-inject.

    #!/bin/bash
    
    ###edit the following
    service=service_name
    email=your@email.address
    sender=admin@your.server
    ###stop editing
    
    host=`hostname -f`
    if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
    then
    echo "$service is running"
    else
    /usr/sbin/service $service start
    if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
    then
    subject="$service at $host has been started"
    message="$service at $host wasn't running and has been started"
    else
    subject="$service at $host is not running"
    message="$service at $host is stopped and cannot be started!!!"
    fi
    /var/qmail/bin/qmail-inject <<EOM
    To: $email
    From: $sender
    Subject: $subject
    
    $message
    
    EOM
    fi
    
  29. hi can u please tell me how i can add this script to my ubuntu server what is the file name where should i place this file and what is the comand to start this script working for it.

    thanks u waiting for ur response.

    • create a file named script.sh
      give it the permission to execute chmod +s script.sh
      run it through shell using DOTslash like that ./script.sh

      🙂

      • create a file named script.sh
        give it the permission to execute chmod +x script.sh
        run it through shell using DOTslash like that ./script.sh

  30. The name of the file doesn’t really matter. But as a good convention you should give the file the .sh extension.
    Where you place the file also isn’t important, just put it somewhere you think is logical and where you can find if when needed.
    To start the file simply type in its location. If you put it in your home folder and called the script “servicechecker.sh” you can call it by typing “~/servicechecker.sh” (without the quotes obviously). When using cron to call the script it would be similar, but in that case I recommend always using the full directory path. (“/home//servicechecker.sh instead of ~/servicechecker.sh”

  31. hi akamaras, can you please tell me how to start the service from script.
    my script is:
    #!/bin/bash
    service=zipgateway

    if ( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )
    then
    echo “$service is running!!!”
    else
    /etc/init.d/$service start
    fi

    showing the log as:/etc/init.d/zipgateway: not found

    • It’s been a while since this post was written. Most linux distributions have switched to systemd since then.
      Replace this line from the script “/etc/init.d/$service start” with “systemctl start $service”

  32. script to check the service is running for a current IP address.Any suggestions?

  33. Rishikkanth

    Haye guys the script was excellent but if we want to check status for two services and we need to check multiple services on one host how can we do that i thought to do with for loop and if loop but i am failed.

  34. Hi Akamaras,

    I have small query regarding Devtest services weekly recycle.

    My requirement was I had devtest services which is running on Devtest Servers . So I want to restart those services in a weekly manner.

    Total 5 Services are there and services are installed into 3 different servers. So need shell script to restart those services from servers by automating without manully …

    Waiting for your reply…

    Regards,
    Naveen B.

  35. How can use this script to check multiple services if they are up?

  36. Works like a charm on CentOS 7

  37. i am using kill -SIGSEV pid_num to stop a process and written a code to automatically restart the process when ever it is stopped .but it was working only once when i use KILL -SIGSEGV to kill the restarted process i am unable to kill that process

  38. Hi Akamaras,

    This is Uday.. I need a shell script for the below requirement. I’m new to Shell Scripting.

    1. Need to check the status of 5 service’s which are running on multiple server’s.
    2. If the service is not running, then it should restart it and check for the status.
    3. We need to find the server list in the below file where the script is running.
    /deployment/opentext/settings/DEV/PUB.settings
    4. Output show look like below.

    ———————————————————————————————-
    Hostname: plentapp010
    Uptime : 03:30:03 up 3:26, 0 users, load average: 0.64, 0.46, 0.38
    ———————————————————————————————-
    Processes              Status
    ——————–    —————–
    activemq * Attempted to restart – Result: Running
    delivery-engine * Attempted to restart – Result: Failed
    command-center  Running
    tomcatappserverForAddOn Running
    apache-tomcat Running

    Thank you.

    Regards,
    Uday

  39. Hello everyone 🙂

    i need a script to check the status of the the server and send the output to my email
    and preferable to restart it if it is down.

    How could i do this?

  40. Ahamed Nawas Mohamed

    i want to do get like this

    1. I have 7 instances and management server
    2. need to restart 1 by 1 httpd service.
    3. first restart 1 instance and get the status through management server. if service up and running it’s going to next server and do the same process. like this i have to do the httpd restart.
    4.

  41. I have around 82 services like the below .to check the status and restart if its down.
    Could you please help me with the code to check and restart without repeating the lines

    ps -ef| grep -i “$path/eventProcessor EVP ACT” |grep -v grep
    if [ $? -ne 0 ]
    then
    echo “process EVP ACT not running”
    nohup $path/eventProcessor EVP ACT &

    fi

    ps -ef| grep -i ” /apps/lp/bin/eventProcessor EVP ALL” |grep -v grep
    if [ $? -ne 0 ]
    then
    echo “process EVP ALL not running”
    nohup /apps/lp/bin/eventProcessor EVP ALL &
    fi

  42. hello

    The script does not run when the cronjob is set , but runs perfectly fine when running the script manually

    Thanks
    AJITH

  43. Hi akamaras,
    I’m also a newbie. Could you help with a script that checks a service on a remote host, and starts the service on my local host if the remote host service isn’t running?

  44. Linux Useful Commands | Linux, DevOps & AWS - pingback on 23/05/2019 at 11:46

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

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