Finding Out Whether a Process Is Running

Problem

You need to determine whether a process is running, and you might or might not already have a process ID (PID).

Solution

If you don’t already have a PID, grep the output of the ps command to see if the program you are looking for is running. See Grepping ps Output Without Also Getting the grep Process Itself, for details on why our pattern is [s]sh.

$ [ "$(ps -ef | grep 'bin/[s]shd')" ] && echo 'ssh is running' || echo 'ssh not running'

That’s nice, but you know it’s not going to be that easy, right? Right. It’s difficult because ps can be wildly different from system to system.

# cookbook filename: is_process_running

# Can you believe this?!?
case `uname` in
    Linux|AIX) PS_ARGS='-ewwo pid,args'   ;;
    SunOS)     PS_ARGS='-eo pid,args'     ;;
    *BSD)      PS_ARGS='axwwo pid,args'   ;;
    Darwin)    PS_ARGS='Awwo pid,command' ;;
esac

if ps $PS_ARGS | grep -q 'bin/[s]shd'; then
    echo 'sshd is running'
else
    echo 'sshd not running'
fi

If you do have a PID, say from a lock file or an environment variable, just search for it. Be careful to match the PID up with some other recognizable string so that you don’t have a collision where some other random process just happens to have the stale PID you are using. Just obtain the PID and use it in the grep or in a -p argument to ps:

# Linux
$ ps -wwo pid,args -p 1394 | grep 'bin/sshd'
 1394 /usr/sbin/sshd

 # BSD
 $ ps ww -p 366 | grep 'bin/sshd'
 366 ?? Is 0:00.76 /usr/sbin/sshd

Discussion

The test and grep portion of the solution requires ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.