Search code examples
bashbackground-processexit-code

Bash & (ampersand) operator


I'm trying to run 3 commands in parallel in bash shell:

$ (first command) & (second command) & (third command) & wait

The problem with this is that if first command fails, for example, the exit code is 0 (I guess because wait succeeds).

The desired behavior is that if one of the commands fails, the exit code will be non-zero (and ideally, the other running commands will be stopped).

How could I achieve this?

Please note that I want to run the commands in parallel!


Solution

  • the best I can think of is:

    first & p1=$!
    second & p2=$!
    ...
    
    wait $p1 && wait $p2 && ..
    

    or

    wait $p1 || ( kill $p2 $p3 && exit 1 )
    ...
    

    however this still enforces an order for the check of processes, so if the third fails immediately you won't notice it until the first and second finishes.