19

Doesn't the bash shell already run the commands one by one and wait for the executed command to finish? So when and why do we need the wait command?

1 Answer 1

38

You use wait if you have launched tasks in background, e.g.

#!/bin/bash
task1 &
task2 &
task3 &
wait
echo done

In this example the script starts three background tasks. These will run concurrently in the background and the wait will wait for all three tasks to finish. Once wait returns, the script continues with processing the echo done.


As pointed out in comment wait can be given a job number (wait %3) or a pid (wait 1234). While it is easy ( using job or ps ) in interactive bash to find those, it might be more difficult in batch mode.

2
  • Adding to this, you can use wait to wait on specific background jobs (pass a PID for the job), and when doing so it will return the exit status of the job when it exits. This is exceedingly useful for more complex asynchronous programming, as well as waiting for all background jobs to exit before exiting the script. Sep 18, 2020 at 23:32
  • @AustinHemmelgarn: Your tip would be complete if you could state how to get the PID of an & job.
    – Joshua
    Sep 20, 2020 at 3:22

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.