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?
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