Bash – How to wait for background jobs in the background

background-processbashjobs

I have the following problem:

$ some_command &     # Adds a new job as a background process
$ wait && echo Foo   # Blocks until some_command is finished
$ wait && echo Foo & # Is started as a background job and is done immediately

What I would like wait & to do is to wait in the background until all other background jobs are finished.

Any way I can achieve that?

Best Answer

At some point, something has to wait for the execution of commands.
However, if you could place your commands inside a couple of functions, you can schedule them to do what you need:

some_command(){
    sleep 3
    echo "I am done $SECONDS"
}

other_commands(){
    # A list of all the other commands that need to be executed
    sleep 5
    echo "I have finished my tasks $SECONDS"
}

some_command &                      # First command as background job.
SECONDS=0                           # Count from here the seconds.
bg_pid=$!                           # store the background job pid.
echo "one $!"                       # Print that number.
other_commands &                    # Start other commands immediately.
wait $bg_pid && echo "Foo $SECONDS" # Waits for some_command to finish.
wait                                # Wait for all other background jobs.
echo "end of it all $SECONDS"       # all background jobs have ended.

If the sleep times are as shown in the code, 3 and 5, then some_command will end before the rest of the jobs, and this will be printed on execution:

one 760
I am done 3
Foo 3
I have finished my tasks 5
end of it all 5

If the sleep times are (for example) 8 and 5, this will be printed:

one 766
I have finished my tasks 5
I am done 8
Foo 8
end of it all 8

Note the order. Also the fact that each part has ended as soon as it was possible for itself (the value of $SECONDS printed).

Related Question