什么命令在链中失败了?

时间:2018-06-17 10:18:39

标签: linux bash

让我们考虑以下代码:

a && b && c && d
echo "Command {xyz} ended with exit code $?"

如果一切顺利,它很简单,因为所有命令都返回0的退出代码。但是如果遇到非零退出代码,是否可以说,哪个命令返回它并打破了链 - 即。 {xyz}应该是什么?

PS。我知道我可以使用嵌套的条件语句,但链接结构非常明确且易于理解 - 我只想为它添加一些分析。

2 个答案:

答案 0 :(得分:4)

您可以尝试以下方式:

{ a; status1=$?; } && { b; status2=$?; }
echo "status1=${status1}, status2=${status2}"

如果您不需要在命令的标准输出中打印输出,您可能会考虑这样的事情:

run_and_check() {
    eval "$@" >/dev/null 2>&1 # you could replace /dev/null by a log file
    echo $?
}

status1=$(run_and_check "a") && status2=$(run_and_check "b")
echo "status1=${status1}, status2=${status2}"

但与第一种更通用且危险性更低的解决方案相比,我们节省的费用不多;)

答案 1 :(得分:2)

有一个功能:

#!/bin/bash    

run() {
  $@ || echo "Command $1 ended with exit code $?"
}

run a && run b && run c && run d