7

I have a script with

for i in 1 2 3 4; do
    do_something $i &
done

And when I call it, it terminates before all do_something terminated. I found this question with many different answers.

Edit: help wait tells me that

If ID is not given, waits for all currently active child processes, and the return status is zero.

Is it not sufficient to just add a single wait at the end?

fabian789
  • 217

2 Answers2

14

Yes, it's enough to use a single wait with no arguments at the end to wait for all background jobs to terminate.

Note that background jobs started in a subshell would need to be waited for in the same subshell that they were started in. You have no instance of this in the code that you show.

Note also that the question that you link to asks about checking the exit status of the background jobs. This would require wait to be run once for each background job (with the PID of that job as an argument).

Kusalananda
  • 333,661
  • This did not work for me. A single line of wait at the end with no parameters, did not help me. I loop over git repositories and pull them. Coming from this question. – Saeed Neamati Jan 26 '22 at 11:50
  • @SaeedNeamati That question and the question linked to in the question above both start background jobs in a subshell but call wait outside that subshell. – Kusalananda Aug 13 '22 at 09:50
-1

In my opinion, even though a single wait without parameters should be sufficient, this is not a good practice (relay on a default behaviour). I would collect the pid returned from each call, and wait for these pids explicitly.

Eran Ben-Natan
  • 568
  • 2
  • 7