Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 896
XåpplI'-I0llwlg'I - Avatar asked Jun 28 '12 06:06

XåpplI'-I0llwlg'I -


People also ask

How do I know if bash is running in the background?

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.

How do I know if background processes are running?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time. This will display the process for the current shell with four columns: PID returns the unique process ID.

How do I know if bash is working?

To find my bash version, run any one of the following command: Get the version of bash I am running, type: echo "${BASH_VERSION}" Check my bash version on Linux by running: bash --version. To display bash shell version press Ctrl + x Ctrl + v.


1 Answers

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
like image 145
Todd A. Jacobs Avatar answered Oct 19 '22 03:10

Todd A. Jacobs