0

I want to run bunch of commands simultaneously and when all of them finished, run another bunch of commands.some thing like this command1 & command2 echo "command 1 and 2 finished" command 3 & command 4

  • 4
    Look into using the wait command. – Raman Sailopal Jan 22 '18 at 8:57
2
command1 &
command2 &

wait
echo 'command1 and command2 have finished'

command3 &
command4 &

wait
echo 'command3 and command4 have finished'

The call to wait will pause the script until all backgrounded tasks have finished executing.

Alternatively (just "for your information"), depending on whether you want command 1 and 2 to run concurrently or not (equivalently for command 3 and 4):

( command1; command2 ) &
echo 'command1 and command2 are running'
wait
echo 'command1 and command2 have finished'

In the above case, command1 and command2 will run in the background, but not concurrently with each other.


Doing

command1 & command2
wait

is equivalent to

command1 &
command2
wait

... which will work, but command2 will not be running in the background and wait will not be called until command2 has finished executing.

1

The actual answer of my question was something like this, special thanks from @raman-sailopal

command1 & command2
wait
echo "command 1 and 2 has finished"
command3 & command4
  • That will work, but thu wait will only wait for command1 as command2 is not run as a background task. The same goes for command4. – Kusalananda Jan 22 '18 at 9:55
0
command1 & command2; echo "command1 & 2 complete" && command3 & command4; echo "command3 & 4 complete"

& runs commands simultaneously

; emulates a new line - i.e. will be run after completion

&& runs once the previous job has finished, provided the previous job was successful (i.e. didn't return any exit code but 0)

  • This doesn’t work: command1 will run in the background, the first echo will run as soon as command2 completes, regardless of whether command1 has finished. Likewise for command3. – Stephen Kitt Jan 22 '18 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.