How to get the exit status of multiple parallel background processes in bash [duplicate]

◇◆丶佛笑我妖孽 提交于 2021-02-08 06:11:48

问题


In Bash, I want to call a command multiple times in parallel, while capturing all the processes exit codes.

I know how to start and wait for them, but wait will only give me the exit code of the last process exiting. I also need the exit code of the shorter lived processes.

Unfortunately I don't have bash 4.3, so wait -n is not an option, nor is gnu parallel as suggested in #3004811

#16032001 pretty much asks the same question but no solution was offered there either.

The only way I can currently think of is writing a helper script that stores the exit codes in a file, but this doesn't sound like a clean solution.


回答1:


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

I was unaware that though the child is immediately reaped by bash, the builtin wait can still access the exit code for the pid.

#!/bin/bash

FAIL=0
PIDS=""

echo "starting"

sleep 5 &
PIDS="$PIDS $!"

sleep 3 &
PIDS="$PIDS $!"

/bin/false &
PIDS="$PIDS $!"

sleep 3 &
PIDS="$PIDS $!"

for job in $PIDS
do
    wait $job || let "FAIL+=1"
    echo $job $FAIL
done

echo $FAIL

if [ "$FAIL" == "0" ];
then
    echo "YAY!"
else
    echo "FAIL! ($FAIL)"
fi

correctly gives

starting
14772 0
14773 0
14774 1
14775 1
1
FAIL! (1)

Only the third process (/bin/false) fails, indicated by the switch from 0 to one in the third line.



来源:https://stackoverflow.com/questions/46193327/how-to-get-the-exit-status-of-multiple-parallel-background-processes-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!