Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if PID exists in Bash

Tags:

bash

shell

pid

I want to stall the execution of my BASH script until a process is closed (I have the PID stored in a variable). I'm thinking

while [PID IS RUNNING]; do sleep 500 done 

Most of the examples I have seen use /dev/null which seems to require root. Is there a way to do this without requiring root?

Thank you very much in advance!

like image 409
JohnP Avatar asked Mar 05 '11 21:03

JohnP


People also ask

How do you know if PID exists?

If you want to know if the process with id $PID exists, you can just do test -d /proc/$PID instead of starting additional processes. Note that you cannot ever know if a process exists in some another PID namespace.

How do I check if a process is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.


2 Answers

kill -s 0 $pid will return success if $pid is running, failure otherwise, without actually sending a signal to the process, so you can use that in your if statement directly.

wait $pid will wait on that process, replacing your whole loop.

like image 62
moonshadow Avatar answered Sep 20 '22 02:09

moonshadow


It seems like you want

wait $pid 

which will return when $pid finishes.

Otherwise you can use

ps -p $pid 

to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).

like image 21
sligocki Avatar answered Sep 24 '22 02:09

sligocki