When I discovered "ps -p pid" would set the exit code to failure if pid wasn't found, I was happy. It seemed a much cleaner and more portable way to decide if a process was running, as opposed to grepping through ps output. However, it looks like the ps command on the Mac (MacOS 10.4) isn't setting the exit code in the case the process isn't found, so you get a false positive (process looks like it's running when it isn't):
% ps -p 2664
PID TT STAT TIME COMMAND
% echo $?
While I would like to use ps -p pid since it's a tight one-liner, this looks like I'm going to have to count how many lines of output ps -p has. Something like this:
test 2 -eq `ps -p $pid | wc -l | xargs expr`
The goal is a line (or lines, if absolutely necessary), which is foremost portable, i.e. works on any many platforms and as many variants of ps as possible.
Any comments or suggestions from the readers?
Edited Jan 23, 2007: Removed the "ps -p" and just left the test command.