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

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

    There are already a lot of answers here, but I am surprised no one seems to have suggested using arrays... So here's what I did - this might be useful to some in the future.

    n=10 # run 10 jobs
    c=0
    PIDS=()
    
    while true
    
        my_function_or_command &
        PID=$!
        echo "Launched job as PID=$PID"
        PIDS+=($PID)
    
        (( c+=1 ))
    
        # required to prevent any exit due to error
        # caused by additional commands run which you
        # may add when modifying this example
        true
    
    do
    
        if (( c < n ))
        then
            continue
        else
            break
        fi
    done 
    
    
    # collect launched jobs
    
    for pid in "${PIDS[@]}"
    do
        wait $pid || echo "failed job PID=$pid"
    done
    

提交回复
热议问题