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?
Best Answer
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).