Search code examples
bashif-statementcentospid

Bash : Check if PID exists with further logic


Question: How do you check if a PID exists and use the result within an IF statement in bash?

Things I've tried

if [ "$(ps -p $pid)" -eq 0 ]; then 
 echo "Running"
else
 echo "Not Running"
fi

if [ "$(kill -0 $pid)" -eq 0 ]; then 
 echo "Running"
else
 echo "Not Running"
fi

Neither of these evaluate correctly no matter how I redirect STDOUT/STDER


Solution

  • How do you check if a PID exists and use the result within an if statement?

    You can capture the output in a variable and then check the exit status:

    output=$(ps -p "$pid")
    if [ "$?" -eq 0 ]; then
      echo "Found"
      echo "$output"
    fi
    

    Just remember that $? is getting reset every time you run a command, so something like the following wont work:

    output=$(ps -p "$pid")
    echo "$output"
    # Now $? will be refering to the exit status of echo
    if [ "$?" -eq 0 ]; then
      echo "Found"
    fi
    

    One can also stick everything together in the if statement:

    if output=$(ps -p "$pid")
    then
      echo "Found: $output"
    fi