How to check if a process id (PID) exists
In a bash script, I want to do the following (in pseudo-code):
if [ a process exists with $PID ]; then
kill $PID
fi
What's the appropriate expression for the conditional statement?
The best way is:
if ps -p $PID > /dev/null
then
echo "$PID is running"
# Do something knowing the pid exists, i.e. the process with $PID is running
fi
The problem with kill -0 $PID
is that the exit code will be non-zero even if the process is running and you don't have permission to kill it. For example:
kill -0 $known_running_pid
and
kill -0 $non_running_pid
have a non-zero exit codes that are indistinguishable for a normal user, but one of them is by assumption running, while the other is not.
Partly related, additional info provided by AnrDaemon: The init process (PID 1) is certainly running on all Linux machines, but not all POSIX systems are Linux. PID 1 is not guaranteed to exist there:
kill -0 1
-bash: kill: (1) - No such process …
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 don't 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 want it to terminate in any case, then just
kill $pid
Otherwise you will have a race condition, where the process might have disappeared after the first kill -0
.
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" >&2
fi
If your system implements procfs interface, you can just check if there is a special file /proc/$PID/status
:
if [ -e /proc/$PID/status ]; then
echo "process exists"
fi
otherwise you can use ps
program:
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.