To achieve this, you need to store the PID of each of the background process of bfoo.sh
. The $!
contains the process id that was last backgrounded by the shell. We append them one at a time to the array and iterate it over later
Remember this runs your background process one after the other since you have wait
on each process id separately.
#!/usr/bin/env bash
pidArray=()
for i in {1..5}; do
./bfoo.sh &
pidArray+=( "$!" )
done
Now wait on each of the processes and in a loop
for pid in "${pidArray[@]}"; do
wait "$pid"
printf 'process-id: %d finished with code %d\n' "$pid" "$?"
done
I have additionally added the exit code of the background process $?
when it finishes, so that any abnormal exit can be debugged.