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 ?

68 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.

      • 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!!!”

      • 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 ])

  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

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>