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

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

    I've had a go at this and combined all the best parts from the other examples here. This script will execute the checkpids function when any background process exits, and output the exit status without resorting to polling.

    #!/bin/bash
    
    set -o monitor
    
    sleep 2 &
    sleep 4 && exit 1 &
    sleep 6 &
    
    pids=`jobs -p`
    
    checkpids() {
        for pid in $pids; do
            if kill -0 $pid 2>/dev/null; then
                echo $pid is still alive.
            elif wait $pid; then
                echo $pid exited with zero exit status.
            else
                echo $pid exited with non-zero exit status.
            fi
        done
        echo
    }
    
    trap checkpids CHLD
    
    wait
    

提交回复
热议问题