Parallel commands in Bash
Bash natively supports a wait command.
Run parallel processes
Using default wait behavior
By default, wait will wait for all child processes to complete before continuing an execution. For most cases, this is sufficient.
1sleep 2 && echo "hi" &
2sleep 2 && echo "hi2" &
3
4# Wait for child processes to finish
5waitUsing the & character at the ending of a line sends the process to the background to complete. Without wait, the the script would end.
The script will complete in 2 seconds.
Output variation 1:
1hi
2hi2Output variation 2:
1hi2
2hiUsing wait with process ids
wait allows for a process id argument value. This may be useful for establishing chained waits.
In the example below, the “hi3” task depends on “hi”; however “hi2” may run in parallel with “hi”.
1sleep 2 && echo "hi" &
2hi_pid=$!
3
4# "hi2" does not require "hi"
5sleep 2 && echo "hi2" &
6
7wait $hi_pid
8
9# "hi3" requires "hi"
10sleep 2 && echo "hi3" &
11
12waitOutput:
1hi2
2hi
3hi3The process id of the last execution is returned using $!.