linux - 如何 "catch"非零退出代码尽管 "set -e"然后回显错误代码

标签 linux bash

我有脚本

#!/bin/bash

set -e

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script" 

脚本的目的是使用 set -e 终止任何非零命令退出代码的执行,除非命令被“捕获”(来自 Java),例如错误命令 asd

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

然而,尽管我“捕获”了错误并且 end of script 打印到终端,错误代码是 0

echo "caught command failure with exit code ${?}"

所以我的问题是如何“捕获”错误命令,并打印该命令的退出代码

编辑

我已经重构了相同结果的脚本,退出代码仍然是 0

#!/bin/bash

set -e

if ! asd ; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script"

最佳答案

只需使用短路:

asd || echo "asd exited with $?" >&2

或者:

if asd; then 
    :
else
    echo asd failed with status $? >&2
fi

你不能做 if ! asd,因为 ! 否定状态并将 $? 设置为 0 如果 asd 退出非零并设置 如果 asd 退出 0,则 $? 为 1。

但请注意,无论哪种情况,最佳做法都是简单地调用 asd。如果失败,它应该发出一条描述性错误消息,而您的附加错误消息只是不必要的冗长信息,具有边际效益。如果 asd 没有发出有用的错误消息,您应该修复它。

关于linux - 如何 "catch"非零退出代码尽管 "set -e"然后回显错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189769/

相关文章:

linux - Ubuntu Linux 服务器不允许我向上滚动/翻页

linux - 将批处理文件函数转换为 bash

linux - 在 Linux 中转换文本文件

python - 在 databricks 集群中使用 init 脚本安装 python 包

linux - bash:用于命令替换的变量中的管道字符

linux - 用换行符替换空格,特殊字符包裹的空格除外

bash - 如何在 ssh session 中执行 scp 命令?

linux - 我不允许在文件名中使用什么字符序列?

c - linux 打开标志中的按位或

linux - 如何使用单独的 VM 服务器来托管数据库来安装 OIM 11gPS2