Skip to content

Commit 532f44a

Browse files
committed
additional/bash/bg.sh: Script to provide example of starting multiple jobs at background and waiting for them to finish
Signed-off-by: Marian Marinov <[email protected]>
1 parent 2f1c7a4 commit 532f44a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

additional/bash/bg.sh

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/bin/bash
2+
3+
# Example script of staring and waiting on a number of tasks at background
4+
5+
cmd='sleep 5'
6+
max_threads=3
7+
for i in {1..5}; do
8+
procs=()
9+
for m in $(seq 1 $max_threads); do
10+
$cmd &
11+
procs+=($!)
12+
done
13+
echo ${procs[*]}
14+
15+
# Wait for all tasks to finish
16+
# After each task is finished, remove it from the array and reassign the rest of the elements
17+
# to the same array, so we can reference the first element.
18+
total=${#procs[*]}
19+
while [[ $total -ne 0 ]]; do
20+
wait ${procs[0]}
21+
echo "PID: ${procs[0]} finished"
22+
unset 'procs[0]'
23+
procs=(${procs[*]})
24+
let total--
25+
done
26+
done

0 commit comments

Comments
 (0)