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

时间:2019-11-06 13:43:01

标签: bash

我已经搜索了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

我不知道该怎么实现...

有人帮我吗?谢谢您的宝贵时间。

1 个答案:

答案 0 :(得分: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