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

后端 未结 30 2486
悲哀的现实
悲哀的现实 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:33

    This works, should be just as a good if not better than @HoverHell's answer!

    #!/usr/bin/env bash
    
    set -m # allow for job control
    EXIT_CODE=0;  # exit code of overall script
    
    function foo() {
         echo "CHLD exit code is $1"
         echo "CHLD pid is $2"
         echo $(jobs -l)
    
         for job in `jobs -p`; do
             echo "PID => ${job}"
             wait ${job} ||  echo "At least one test failed with exit code => $?" ; EXIT_CODE=1
         done
    }
    
    trap 'foo $? $$' CHLD
    
    DIRN=$(dirname "$0");
    
    commands=(
        "{ echo "foo" && exit 4; }"
        "{ echo "bar" && exit 3; }"
        "{ echo "baz" && exit 5; }"
    )
    
    clen=`expr "${#commands[@]}" - 1` # get length of commands - 1
    
    for i in `seq 0 "$clen"`; do
        (echo "${commands[$i]}" | bash) &   # run the command via bash in subshell
        echo "$i ith command has been issued as a background job"
    done
    
    # wait for all to finish
    wait;
    
    echo "EXIT_CODE => $EXIT_CODE"
    exit "$EXIT_CODE"
    
    # end
    

    and of course, I have immortalized this script, in an NPM project which allows you to run bash commands in parallel, useful for testing:

    https://github.com/ORESoftware/generic-subshell

提交回复
热议问题