如何在bash中检测许多命令成功与否?

问题描述 投票:1回答:1

我已经搜索了how to detect the a command success or not in bash。例如:https://askubuntu.com/questions/29370/how-to-check-if-a-command-succeeded/29379#29379有人建议使用$?检测命令是否成功。

我想做很多任务,然后检查任务是否正常。

首先,我会逐一检查。它以串行方式。

# first
./a.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi
# second
./b.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi
# third
./c.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi

任务之间没有任何限制,因此我想将脚本转移为并行方式。我想在后台提交命令,并在命令完成后进行检查。我想要类似的内容

# submit all task to back ground
./a.out &
./b.out &
./c.out &

# wait they all finished ...
# wait a
# wait b
# wait c

# do some check ...
# check a
# check b
# check c

我不知道该如何实现...

知道有人帮我吗?谢谢您的时间。

bash
1个回答
2
投票

来自man wait(1)

退出状态顶部

   If one or more operands were specified, all of them have terminated
   or were not known by the invoking shell, and the status of the last
   operand specified is known, then the exit status of wait shall be the
   exit status information of the command indicated by the last operand
   specified. [...]

它看起来像这样:

# submit all task to back ground
./a.out &
apid=$!
./b.out &
bpid=$!
./c.out &
cpid=$!

# wait they all finished ...
wait "$apid"
aret=$?
wait "$bpid"
bret=$?
wait "$cpid"
cret=$?

# do some check ...
if ((aret)); then
   echo a failed
fi
if ((bret)); then
   echo b failed
fi
if ((cret)); then
   echo c failed
fi
© www.soinside.com 2019 - 2024. All rights reserved.