chrisg
chrisg

Reputation: 41655

Check if process is running

I am trying to check if a process is running. If it is running I want a return value of 'OK' and if not a return value of 'Not OK'. I can only use 'ps' without any other arguments attached (eg. ps -ef) if thats the correct term. The code I have is:

if ps | grep file; then  echo 'OK'; else  echo 'NO'; fi

The problem with this is that it does not search for the exact process and always returns 'OK', I don't want all the information to appear I just want to know if the file exists or not.

Upvotes: 7

Views: 17658

Answers (7)

user3182551
user3182551

Reputation: 373

What about "pgrep"?

$ pgrep -x foo
xxxx
$

where xxxx is the pid of the binary running with the name foo. If foo is not running, then no output.

Also:

$ if [[ pgrep -x foo ]]; then echo "yes"; else echo "no" ; fi;

will print "yes" if foo is running; "no" if not.

see pgrep man page.

Upvotes: 2

Nischal Hp
Nischal Hp

Reputation: 435

if ps | grep file | grep -v grep;
then echo 'ok';
else echo 'no';

grep -v grep makes sure that the result you get is not the grep statement in execution.

Upvotes: 0

mgalgs
mgalgs

Reputation: 16779

When I know the pid I prefer:

[ -d /proc/<pid> ] && echo OK || echo NO

Upvotes: 1

Guest67
Guest67

Reputation: 43

There is a solution with grep as well:

if [ "$(ps aux | grep "what you need" | awk '{print $11}')" == "grep" ]; then
...
elif [ ... ]; then
...
else
...
fi

This works fine in Debian 6, not sure about other distros. '{print $11}' is needed, because the sytem treats grep as a process as well.

Upvotes: -1

user unknown
user unknown

Reputation: 36229

Spare grep for real problems:

ps -C file

avoids the problem of using grep altogether.

Upvotes: 8

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

ps | grep -q '[f]ile'

Upvotes: 2

tangens
tangens

Reputation: 39733

Your code always returns 'OK', because grep finds itself in the process list ('grep file' contains the word 'file'). A fix would be to do a `grep -e [f]ile' (-e for regular expression), which doesn't find itself.

Upvotes: 10

Related Questions