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

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

    #!/bin/bash
    set -m
    for i in `seq 0 9`; do
      doCalculations $i &
    done
    while fg; do true; done
    
    • set -m allows you to use fg & bg in a script
    • fg, in addition to putting the last process in the foreground, has the same exit status as the process it foregrounds
    • while fg will stop looping when any fg exits with a non-zero exit status

    unfortunately this won't handle the case when a process in the background exits with a non-zero exit status. (the loop won't terminate immediately. it will wait for the previous processes to complete.)

提交回复
热议问题