Check if process is running

16,722

Solution 1

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.

Solution 2

Spare grep for real problems:

ps -C file

avoids the problem of using grep altogether.

Solution 3

ps | grep -q '[f]ile'

Solution 4

When I know the pid I prefer:

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

Solution 5

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.

Share:
16,722
chrisg
Author by

chrisg

All things serverless at the minute. Enjoy travelling and getting my hands on any piece of technology that is of course going to make my life amazing :)

Updated on June 21, 2022

Comments

  • chrisg
    chrisg almost 2 years

    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.