1

I want to write a shell scripts that executes a few commands and waits for all of them to terminate.

I think what I would have to do is use

      cmd1 &
      cmd2 &
      cmd3 &
      ....

etc.

but what I don't know is how to wait for them to terminate.

any ideas?

kloop
  • 4,537
  • 13
  • 42
  • 66

3 Answers3

1

Just use the wait command without any args:

cmd1 &
cmd2 &
cmd3 &
wait

This will make bash wait for all unfinished children. This will work as long as you don't have other background tasks that you need to continue as well.

FatalError
  • 52,695
  • 14
  • 99
  • 116
0

This question has the answer to your problem. :)

You would simply wait for all running jobs by calling the wait command.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Community
  • 1
  • 1
Gung Foo
  • 13,392
  • 5
  • 31
  • 39
  • ";" wouldn't work for me because I want them to all run together in the background. Kind of like forking and waiting for all the processes you forked to terminate. – kloop Sep 27 '12 at 17:43
0

This example seems to work.

[stou$ ~]$ (sleep 1 ; echo 1) & (sleep 4 ; echo 4) & (sleep 3 ; echo 3)&  wait; echo done
[1] 13651
[2] 13652
[3] 13653
1
[1]   Done                    ( sleep 1; echo 1 )
3
4
[2]-  Done                    ( sleep 4; echo 4 )
[3]+  Done                    ( sleep 3; echo 3 )
done
[stou$ ~]$ 
stou
  • 63
  • 6