Shell script wait for background command

background-processscriptingshell

I am writing a script, but there is something I need that I can't find a way to do it…

I need to make a command in background "command1 &" and then somewhere in the script I need to wait for it to finish before I do command2. Basically, I need this:

NOTE: each command runs in a specific directory! at the end of the while loop my command1 created 4 directory's, where in each one run the specific process so the total of process running are 4

a=1

while [$a -lt 4 ]

     . command1
   #Generates 1 Process  

     a= `export $a +1`
done

   #Wait until the 4 process end and then run the command2 

    . command2

I've seen something about a wait command with the pid process number, but that didn't work also.

Best Answer

You can use the command wait PID to wait for a process to end.

You can also retrieve the PID of the last command with $!

In your case, something like this would work:

command1 & #run command1 in background
PID=$! #catch the last PID, here from command1
command2 #run command2 while command1 is running in background
wait $PID #wait for command1, in background, to end
command3 #execute once command1 ended

Following your edit, as you have multiple PIDs and you know them, you can do that:

command1 & #run command1 in background
PID1=xxxxx
PID2=yyyyy
PID3=xxyyy
PID4=yyxxx
command2 #run command2 while command1 is running in background
wait $PID1 $PID2 $PID3 $PID4 #wait for the four processes of command1, in background, to end
command3 #execute once command1 ended
Related Question