How to check if a process id (PID) exists How to check if a process id (PID) exists bash bash

How to check if a process id (PID) exists


The best way is:

if ps -p $PID > /dev/nullthen   echo "$PID is running"   # Do something knowing the pid exists, i.e. the process with $PID is runningfi

The problem with:

kill -0 $PID

is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:

kill -0 1

and

kill -0 $non-running-pid

have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".

The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?


To check for the existence of a process, use

kill -0 $pid

But just as @unwind said, if you're going to kill it anyway, just

kill $pid

or you will have a race condition.

If you want to ignore the text output of kill and do something based on the exit code, you can

if ! kill $pid > /dev/null 2>&1; then    echo "Could not send SIGTERM to process $pid" >&2fi


if [ -n "$PID" -a -e /proc/$PID ]; then    echo "process exists"fi

or

if [ -n "$(ps -p $PID -o pid=)" ]

In the latter form, -o pid= is an output format to display only the process ID column with no header. The quotes are necessary for non-empty string operator -n to give valid result.