2

I Have a script foo.sh that launches 5 process of bfoo.sh in background like this :

for i in {1..5}
do 
  ./bfoo.sh &
done 
wait 
echo ok

and I use it like this :

./foo.sh

In foo.s after the for loop, I want to do something like i.e. for each process bfoo.sh terminated do

echo $PID_Terminated
Inian
  • 80,270
  • 14
  • 142
  • 161

1 Answers1

2

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.

Inian
  • 80,270
  • 14
  • 142
  • 161