Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to check if service is running [duplicate]

Tags:

bash

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.

like image 523
DroidOS Avatar asked Dec 10 '22 23:12

DroidOS


1 Answers

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.

like image 104
Oleg Mikheev Avatar answered Jan 07 '23 07:01

Oleg Mikheev