37

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.

2 Answers 2

64
j1 &
j2 &
j3 &
wait $(jobs -p)
dostuffwithresults
Sign up to request clarification or add additional context in comments.

4 Comments

+1, but the argument to wait is not required in this case as it's the default.
@JohanLundberg, indeed, I had no idea ;-)
Reason to add the argument to wait is if you wish to collect status from the jobs. Unfortunately, only returns the status of the last process in list, so would have to iterate to check/gather all status'
some explanation how and why this works would be great
1

something like this should work

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

    ./dostuffwithresults

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.