2

I wanted to launch several commands in parallel by using a for loop, each command can take more or less time, and I want to call another command at the end of the script. Here is a minimal example:

#!/bin/bash

function test {
    length=$1
    sleep $length

    echo "$length"
    echo "-----"
}

# http://www.cyberciti.biz/faq/bash-for-loop-array/    
array=( 5 1 3 )

for time in "${array[@]}"
do
    test $time &
done

Here is the result:

$ bash ~/test.sh && echo "OK"
OK
$ 1
-----
3
-----
5
-----

As you can see, OK is displayed before the script ended, this is logical since I called test in background with &. I can't add a test on the last test call since it can end before the other calls. I would like that the script exit only once all the test instances called in background are ended.

Here is what the result I'm trying to obtain:

$ bash ~/test.sh && echo "OK"
1
-----
3
-----
5
-----
OK
$ 

How can I get this output?

1 Answer 1

4

You have to wait after the for loop, so all currently active child processes are waited for:

for time in "${array[@]}"
do
    test "$time" &
done

wait
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.