cashman04
cashman04

Reputation: 1173

Run subshell until all others have completed in bash

So say I have something like:

#!/bin/bash
testfunc(){
    echo "blah"
    sleep 30
}

for blah in blahs; do
    testfunc &
done

wait

The script I have is calling a bunch of my functions in the bg, and waiting for them all to finish with no problem... But what I need to do is have another function that starts at the beginning of my script, and runs until after my wait, and then finishes.

#!/bin/bash
testfunc(){
    echo "blah"
    sleep 30
}

gatherloadavg(){
while true; do
    echo "my load averages and other performance data I want" >> blah.txt
done
}

gatherloadavg &
for blah in blahs; do
    testfunc &
done

wait

Upvotes: 1

Views: 39

Answers (1)

Digital Trauma
Digital Trauma

Reputation: 15996

wait takes an optional list of PIDs to wait on. So you should be able to do something like this:

gatherloadavg &
statspid=$!

for blah in blahs; do
    testfunc &
    pidlist="$pidlist $!"
done

wait $pidlist

kill $statspid

Upvotes: 2

Related Questions