#!/bin/bash # when running "some commands" in the background in your script with '&' # and want to wait until they are finished, # you can check the number of background jobs in a loop with the jobs command while [[ $(jobs -r | wc -l) -gt 0 ]]; do sleep 1 done
Here is what the above code is Doing:
1. The jobs command lists all the background jobs.
2. The -r option tells jobs to only list running jobs.
3. The wc -l command counts the number of lines in the output of jobs.
4. The [[ ]] is a bash construct that allows you to do a test.
5. The -gt 0 means “greater than zero”.
6. The sleep 1 command pauses the script for one second.
7. The loop will continue until there are no more background jobs.