Question

I have a pid stored in a file:

echo 394 > pid_stored

I'm checking if a pid is running with:

kill -0 $(cat pid_stored) 2> /dev/null || echo "PID not running"

which works like a charm, but if I want to do multiple actions in the true or false case I guess I need a if then fi structure. But for some reason I can't figure out [ or [[ do not evaluate in the same way:

if [[ $(kill -0 $(cat pid_stored) 2> /dev/null) ]]
then echo "PID IS NOT RUNNING"
fi

does not work, it always evaluates as true. The error streams get directed with 2> to /dev/null since kill -0 evaluates as true if the pid exists or fails

Thanks!

Was it helpful?

Solution

Remove [[ and ]] since that is used for evaluating an expression:

if kill -0 $(<pid_stored) 2> /dev/null
then
   echo "PID IS RUNNING"
else
   echo "PID IS NOT RUNNING"
fi

PS: You can avoid cat also with $(<pid_stored)

To negate you can use:

if ! kill -0 $(<pid_stored) 2> /dev/null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top