1

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

1
  • 4
    Look into using the wait command. Jan 22, 2018 at 8:57

3 Answers 3

5
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.

3
  • Problem is that I have some other tasks running already in the background. Lets call them &1 and &2. Is there a version of this where I can capture the task ids of command1 and command2, then do a wait &3 &4? Ta.
    – Leo
    Nov 28, 2019 at 11:11
  • 1
    @Leo The process ID (PID) of the most recently started background task is available in $!. You could save these in an array (pids+=( "$!" ) after starting a job) and then wait for them (wait "${pids[@]}"). That's assuming you have a shell that supports arrays.
    – Kusalananda
    Nov 28, 2019 at 11:22
  • Thanks for that. I'll try. In the meantime maybe you could add the answer here: unix.stackexchange.com/questions/554602/…
    – Leo
    Nov 28, 2019 at 11:32
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
1
  • 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, 2018 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)

1
  • 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. Jan 22, 2018 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .