5

I have written up the following script

#! /bin/bash
function checkIt()
{
 ps auxw | grep $1 | grep -v grep > /dev/null

 if [ $? != 0 ]
 then
   echo $1"bad";
 else
   echo $1"good";
 fi;
}

checkIt "nginx";
checkIt "mysql";
checkIt "php5-fpm";

The problem here appears to be with the last check checkIt "php5-fpm" which consistently returns php5-fpmbad. The trouble appears to arise due to the hyphen. If I do just checkIt "php5" I get the expected result. I could actually get away with it since I do not have any other process that starts with or contains php5. However, it turns into a hack that will rear up its ugly head one day. I'd be most grateful to anyone who might be able to tell me how to get checkIt "php5-fpm" to work.

DroidOS
  • 8,530
  • 16
  • 99
  • 171
  • you realize that if you run application with command line `vi nginx.xml` your script is going to think nginx is running? – Oleg Mikheev May 07 '15 at 06:14
  • Once again - the comment is pretty much orthogonal to my question. – DroidOS May 07 '15 at 07:02
  • 1
    Probably make no difference but you should really quote `"$1"` –  May 07 '15 at 09:00
  • If someone else on the machine is running a command like `vim nginx-instructions.txt`, your function would report that nginx is running, whether or not it actually is. Don't reinvent the many service monitoring programs that already exist. – chepner May 07 '15 at 13:12

2 Answers2

9

The normal way to check if service is running or not in *nix is by executing this:

/etc/init.d/servicename status

e.g.

/etc/init.d/mysqls status

These scripts check status by PID rather than grepping ps output.

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
  • this is correct for linux where the application is actually registered as a service like it should be, for other environment that have `bash`, like OSX for example, this would not be the correct solution. –  May 07 '15 at 06:18
  • @Oleg Mikheev I have downvoted your answer. If I had wanted to know "How do I check the status of a running process" I would have asked that question. You have answered an entirely different question. If you must know - I am not using `etc/init.d/proc status` or `service proc status` because the answer that is returned is not consistent. Most often it is `proc is running` but, for instance, php5-fpm returns `php5-fpm start/running` or `php5-fpm stop/waiting` – DroidOS May 07 '15 at 06:58
  • 5
    To be fair to Oleg, you actually did ask the question "Bash script to check if service is running", and Oleg answered exactly that. – wallenborn May 07 '15 at 07:46
4

Add word boundaries and a negative lookahead regex to your grep:

#!/bin/bash
function checkIt()
{
 ps auxw | grep -P '\b'$1'(?!-)\b' >/dev/null
 if [ $? != 0 ]
 then
   echo $1"bad";
 else
   echo $1"good";
 fi;
}

checkIt "nginx"
checkIt "mysql"
checkIt "php5-fpm"
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52