Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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.

like image 366
Colin Avatar asked Jan 24 '12 20:01

Colin


People also ask

Does a bash script wait for command to finish?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

How do I make bash script wait?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Does bash run commands in parallel?

GNU parallel examples to run command or code in parallel in bash shell. From the GNU project site: GNU parallel is a shell tool for executing jobs in parallel using one or more computers. A job can be a single command or a small script that has to be run for each of the lines in the input.


2 Answers

j1 & j2 & j3 & wait $(jobs -p) dostuffwithresults 
like image 138
Michael Krelin - hacker Avatar answered Nov 08 '22 04:11

Michael Krelin - hacker


something like this should work

    #!/bin/bash     while [ `pgrep job*` ]     do      echo 'waiting'     done      ./dostuffwithresults 
like image 21
Harry Forbess Avatar answered Nov 08 '22 04:11

Harry Forbess