How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

后端 未结 30 2827
悲哀的现实
悲哀的现实 2020-11-22 03:50

How to wait in a bash script for several subprocesses spawned from that script to finish and return exit code !=0 when any of the subprocesses ends with code !=0 ?

S

30条回答
  •  执念已碎
    2020-11-22 04:30

    How about simply:

    #!/bin/bash
    
    pids=""
    
    for i in `seq 0 9`; do
       doCalculations $i &
       pids="$pids $!"
    done
    
    wait $pids
    
    ...code continued here ...
    

    Update:

    As pointed by multiple commenters, the above waits for all processes to be completed before continuing, but does not exit and fail if one of them fails, it can be made to do with the following modification suggested by @Bryan, @SamBrightman, and others:

    #!/bin/bash
    
    pids=""
    RESULT=0
    
    
    for i in `seq 0 9`; do
       doCalculations $i &
       pids="$pids $!"
    done
    
    for pid in $pids; do
        wait $pid || let "RESULT=1"
    done
    
    if [ "$RESULT" == "1" ];
        then
           exit 1
    fi
    
    ...code continued here ...
    

提交回复
热议问题