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

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


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    jobsfi


You can check if a signal is deliverable

./script2 &myPid=$!sleep 5if kill -0 "$myPid"; then    script3 &    waitfi


To expand on fduff's answer you can use the jobs builtin:

if jobs %%; then    exec ./script3.sh &    waitfi

jobs %% prints the job ID of the most recent background process (the "current job") and returns 0 on success or 1 if there is no such job.