Bash script to check if a service is running

I wrote 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 is with the last check checkIt "php5-fpm"

that php5-fpmbad returns sequentially. The problem arises from the hyphen. If I only do checkIt "php5"

, I get the expected result. I could handle this as I don't have another process that starts with php5 or contains it. However, it turns into a hack that will one day raise its ugly head. I would be very grateful to anyone who could tell me how to get checkIt "php5-fpm" to work.

+3


source to share


2 answers


The usual way to check if a service is running or not on * nix is ​​by doing this:

/etc/init.d/servicename status

      

eg.



/etc/init.d/mysqls status

      

These scripts check the status using the PID, not grepping ps output.

+6


source


Add word boundaries and negative lookahead regex

to yours 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"

      

+1


source







All Articles