Colin
Colin

Reputation: 10810

Can a bash script run simultaneous commands then wait for them to complete?

I want to write a bash script where I run two commands simultaneously, then continue when they both complete.

Here's something that doesn't work, but I'll put it here to illustrate what I'm trying to do:

#!/bin/bash
./job1 &
./job2
./dostuffwithresults

The script will run both job1 and job2 at the same time, but will only wait for job2 to finish before continuing. If job1 takes longer, then the results might not be ready for the final command.

Upvotes: 37

Views: 30064

Answers (2)

Harry Forbess
Harry Forbess

Reputation: 2134

something like this should work

    #!/bin/bash
    while [ `pgrep job*` ]
    do 
    echo 'waiting'
    done

    ./dostuffwithresults

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

j1 &
j2 &
j3 &
wait $(jobs -p)
dostuffwithresults

Upvotes: 64

Related Questions