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

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

    solution to wait for several subprocesses and to exit when any one of them exits with non-zero status code is by using 'wait -n'

    #!/bin/bash
    wait_for_pids()
    {
        for (( i = 1; i <= $#; i++ )) do
            wait -n $@
            status=$?
            echo "received status: "$status
            if [ $status -ne 0 ] && [ $status -ne 127 ]; then
                exit 1
            fi
        done
    }
    
    sleep_for_10()
    {
        sleep 10
        exit 10
    }
    
    sleep_for_20()
    {
        sleep 20
    }
    
    sleep_for_10 &
    pid1=$!
    
    sleep_for_20 &
    pid2=$!
    
    wait_for_pids $pid2 $pid1
    

    status code '127' is for non-existing process which means the child might have exited.

提交回复
热议问题