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

后端 未结 30 2452
悲哀的现实
悲哀的现实 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've just been modifying a script to background and parallelise a process.

    I did some experimenting (on Solaris with both bash and ksh) and discovered that 'wait' outputs the exit status if it's not zero , or a list of jobs that return non-zero exit when no PID argument is provided. E.g.

    Bash:

    $ sleep 20 && exit 1 &
    $ sleep 10 && exit 2 &
    $ wait
    [1]-  Exit 2                  sleep 20 && exit 2
    [2]+  Exit 1                  sleep 10 && exit 1
    

    Ksh:

    $ sleep 20 && exit 1 &
    $ sleep 10 && exit 2 &
    $ wait
    [1]+  Done(2)                  sleep 20 && exit 2
    [2]+  Done(1)                  sleep 10 && exit 1
    

    This output is written to stderr, so a simple solution to the OPs example could be:

    #!/bin/bash
    
    trap "rm -f /tmp/x.$$" EXIT
    
    for i in `seq 0 9`; do
      doCalculations $i &
    done
    
    wait 2> /tmp/x.$$
    if [ `wc -l /tmp/x.$$` -gt 0 ] ; then
      exit 1
    fi
    

    While this:

    wait 2> >(wc -l)
    

    will also return a count but without the tmp file. This might also be used this way, for example:

    wait 2> >(if [ `wc -l` -gt 0 ] ; then echo "ERROR"; fi)
    

    But this isn't very much more useful than the tmp file IMO. I couldn't find a useful way to avoid the tmp file whilst also avoiding running the "wait" in a subshell, which wont work at all.

提交回复
热议问题