How to check whether a background job is alive? (bash)

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · Jun 28, 2012 · Viewed 21.9k times · Source

I have the following bash script, we can call it script1.sh:

#!/bin/bash

exec ./script2.sh &

sleep 5

if job1 is alive then #<--- this line is pseudo-code!
    exec ./script3.sh &
    wait
fi

As can be seen, the script executes script2.sh as a background job and then waits 5 seconds (so script2.sh can do some initialization stuff). If the initialization succeeds, the script2.sh job will still be alive, in which case I also want to start script3.sh concurrently; if not, I just want to quit.

However, I do not know how to check whether the first job is alive, hence the line of pseudo-code. So, what should go in its place?

Answer

Todd A. Jacobs picture Todd A. Jacobs · Jun 28, 2012

You can get the PID of the most recent background job with $!. You could then check the exit status of ps to determine if that particular PID is still in the process list. For example:

sleep 30 &
if ps -p $! >&-; then
    wait $!
else
    jobs
fi