-   Linux - General (
-   -   How to determine whether a PROCESS is running, by a SHELL program? (

yuzuohong 01-21-2003 07:12 PM

How to determine whether a PROCESS is running, by a SHELL program?
Hi all,

For instance,
[root@svr1 root]# ps -ef |grep squid
nobody 6354 1 0 Jan20 ? 00:00:00 /cache/squid/bin/squid
root 17300 17212 1 08:45 pts/1 00:00:00 grep squid
[root@svr1 root]#
I need to write an if-then BASH shell to determine if a PROCESS is running.
I take SQUID as an example.
That should be something like this:
if [squid is running]; then
{echo "good"};
echo "bad";
Please give me some guide. Thank you in advance.


Bert 01-21-2003 07:25 PM

You need to look for the "Introduction to BASH Programming" on the Internet or in the links section on the forum.

If it's a process you've invoked from the command line, use the command


to see a list of process invoked from your tty. If you want to see it from a script, look at

man test

and the syntax

if [ -test condition ]; then
do something
do something else

You can compare strings using this method and return a boolean TRUE or FALSE.

Also look at parsing the output of ps.

That's as much guidance as you should need (you don't want me to write it for you surely?)


jdc2048 01-21-2003 07:40 PM

The answer is in your post, you just need to put it all together.

if ( `ps -ef | grep squid | grep -v grep | wc -l` -eq 1 )
echo "good"
echo "not so good"

You could also use the pgrep utility which returns the process id. As shown below.

if (pgrep squid > 0)
echo "squid is running"
echo "squid is dead"

for some reason the code tag doesn't seem to work right now.

unSpawn 01-21-2003 07:54 PM

...also on any SysV system the easy way would be to check the script that exists as /etc(/rc.d)/init.d/<servicename> with the "status" arg.

RH also got /sbin/pidof as an pgrep equiv. btw:
case $(/sbin/pidof squid 2>&1> /dev/null; echo $?) in
0) exit 0;; *) echo it aint runnin;; esac

yuzuohong 01-21-2003 08:41 PM


Thank you all so much.
I really need to learn much more in this field...

All times are GMT -5. The time now is 03:36 PM.