Search code examples
bashparallel-processingjobs

Executing a command (only) when prior jobs are finished in Bash


I am trying to ensure that a command is run serially after parallel commands have been terminated.

command1 &
command2 &
command3

In the above example, command1 and command2 are launched in background at the same time, but command3 is run soon after. I know this is expected behaviour in Bash, but I was wondering if there was a way for command3 to be launched after command1 and command2 are terminated.

It is probably possible to do:

(command1; touch done1) &
(command2; touch done2) &
while [ ! -f done1 ] && [ ! -f done2 ]; do sleep 1000; done
command3

...but if a more elegant solution is available I will take it. The join needs to be passive as these commands are destined to be used in PBS queues. Any ideas? Thanks in advance.


Solution

  • You can use wait without arguments to wait for all previous jobs to complete:

    command1 &
    command2 &
    wait
    command3