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

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

    I see lots of good examples listed on here, wanted to throw mine in as well.

    #! /bin/bash
    
    items="1 2 3 4 5 6"
    pids=""
    
    for item in $items; do
        sleep $item &
        pids+="$! "
    done
    
    for pid in $pids; do
        wait $pid
        if [ $? -eq 0 ]; then
            echo "SUCCESS - Job $pid exited with a status of $?"
        else
            echo "FAILED - Job $pid exited with a status of $?"
        fi
    done
    

    I use something very similar to start/stop servers/services in parallel and check each exit status. Works great for me. Hope this helps someone out!

提交回复
热议问题