linux - 什么命令在链中失败?

标签 linux bash

让我们考虑以下代码:

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

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

附言。我知道我可以改用嵌套条件语句,但链接结构非常清晰易懂 - 我只想对其进行一些分析。

最佳答案

你可以尝试类似的东西:

{ 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}"

但与第一个更通用且危险性更小的解决方案相比,我们并没有节省太多 ;)

关于linux - 什么命令在链中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895695/

相关文章:

linux - 如何使用调试版的 libc

regex - find 在终端中有效,但在 bash 脚本中失败

mysql - 从数据库sql文件恢复单个mysql表

bash - 提取匹配 "foo"的文件的最后 10 行

linux - XKB_DEFAULT_OPTIONS=grp :shift_caps_switch with more than two keyboard layouts

linux - 如何找到每个节点(分支)的树的最大深度

bash - 使用awk过滤时如何保留文件头

python - 来自 python os.system `RTNETLINK answers: No such file or directory` 的错误答案

linux - .htaccess 将 index.php 重定向到/

linux - 自动设置/部署开发环境