我有脚本
#!/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
退出非零并设置 如果
为 1。asd
退出 0,则 $?
但请注意,无论哪种情况,最佳做法都是简单地调用 asd
。如果失败,它应该发出一条描述性错误消息,而您的附加错误消息只是不必要的冗长信息,具有边际效益。如果 asd
没有发出有用的错误消息,您应该修复它。
关于linux - 如何 "catch"非零退出代码尽管 "set -e"然后回显错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57189769/