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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With