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

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

    Here is simple example using wait.

    Run some processes:

    $ sleep 10 &
    $ sleep 10 &
    $ sleep 20 &
    $ sleep 20 &
    

    Then wait for them with wait command:

    $ wait < <(jobs -p)
    

    Or just wait (without arguments) for all.

    This will wait for all jobs in the background are completed.

    If the -n option is supplied, waits for the next job to terminate and returns its exit status.

    See: help wait and help jobs for syntax.

    However the downside is that this will return on only the status of the last ID, so you need to check the status for each subprocess and store it in the variable.

    Or make your calculation function to create some file on failure (empty or with fail log), then check of that file if exists, e.g.

    $ sleep 20 && true || tee fail &
    $ sleep 20 && false || tee fail &
    $ wait < <(jobs -p)
    $ test -f fail && echo Calculation failed.
    

提交回复
热议问题