How to run a command when a set of parallel ones had success?

Viewed 65

I would like to run two commands in bash at the same time, wait for the success of both, and then run a third command. In addition, I would like to include this into a time command. Schematically:

time { { cmd_1 & cmd_2 & } && cmd 3; } &> time.log

If, for example, I run:

 time { { echo "hi" & sleep 5 & } && echo "ok"; } &> time.log

I get "ok" printed out immediately, without waiting for the success of the commands between curly brackets. Moreover, the time.log file contains the standard error and standard output of the two commands in brackets but the output of time is printed in the terminal only, not in the file.

I am sure I am missing something clear and easy!

2 Answers

Something like this:

time (
    ( sleep 5; exit 1 ) & pid1=$!                      # process returns 1 and causes nok
    ( sleep 6; exit 0 ) & pid2=$!
    wait $pid1 && wait $pid2 && echo aok || echo nok   # wait for both and act accordingly
) 2> time_out                                          # time outputs to std_err

outputs

nok

as the first bg process returns 1.

wait returns when all child processes have finished, ignoring their exit status. wait -n returns when the next one finishes and returns its exit status.

Since you have two child processes you can chain two wait -ns.

time { echo "hi" & sleep 5 & wait -n && wait -n && echo "ok"; } &> time.log
Related