Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

linux - Bash parallel execution and exit code

I would like to run multiple commands in parallel in a bash script, but if any of these commands fails (returns a non-zero exit code), the script exit code must be non-zero.

I have tried to use sem (https://www.gnu.org/software/parallel/sem.html):

cat >script.sh <<EOF
sem -j+0 "sleep 2; echo 1"
sem -j+0 "sleep 4; exit 1; echo 2"
sem -j+0 "sleep 6; echo 3"
sem --wait
EOF
bash script.sh; echo $?

and just background the process:

cat >script.sh <<EOF
{sleep 2; echo 1} &
{sleep 4; exit 1; echo 2} &
{sleep 6; echo 3} &
wait
EOF
bash script.sh; echo $?

In both cases, the overall exit code is always 0.

Any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

but if any of these commands fails (returns a non-zero exit code), the script exit code must be non-zero.

So write that condition.

childs=();
{ sleep 0.2; echo 1 ;} &
childs+=($!);
{ sleep 0.4; exit 1; echo 2; } &
childs+=($!);
{ sleep 0.6; echo 3; } &
childs+=($!);

ret=0;
for i in "${childs[@]}"; do
     if ! wait "$i"; then ret=1; fi
done
echo "ret=$ret"
exit "$ret"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...