Skip to main content
7 of 7
Remove unnecessary "status" check if directory exists already. Use more shell-agnostic `test` command. Escape the PID variable as general programming hygiene.
VasiliNovikov
  • 10.5k
  • 5
  • 53
  • 65

On systems that implement procfs interface such as Linux, you can just check if /proc/$PID exists:

if test -d /proc/"$PID"/; 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.

user2683246
  • 3.6k
  • 32
  • 31