简体   繁体   English

尽管设置了“ -e”,但如何“捕获”非零退出代码,然后回显错误代码

[英]How to “catch” non-zero exit-code despite “set -e” then echo error code

I have script 我有剧本

#!/bin/bash

set -e

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

echo "end of script" 

purpose of script is to terminate execution on any non zero command exit code with set -e except when command is "caught" (comming from Java) as in case of bad command asd 脚本的目的是使用set -e终止在任何非零命令退出代码上的执行,除非命令被“捕获”(来自Java)(如出现错误的命令asd

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

however, though I "catch" the error and end of script prints to terminal, the error code is 0 但是,尽管我“捕获”了错误并且end of script打印到了终端,但错误代码为0

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

so my question is how can I "catch" a bad command, and also print the exit code of that command? 所以我的问题是我如何才能“捕获”一个错误的命令,并同时打印该命令的exit code

edit 编辑

I have refactored script with same result, exit code is still 0 我重构了脚本,结果相同,退出代码仍为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

how can I "catch" a bad command, and also print the exit code of that command? 如何“捕获”错误的命令,并打印该命令的退出代码?

Often enough I do this: 我经常这样做:

asd && ret=$? || ret=$? 
echo asd exited with $ret

The exit status of the whole expression is 0 , so set -e doesn't exit. 整个表达式的退出状态为0 ,因此set -e不会退出。 If asd succedess, then the first ret=$? 如果asd成功,则第一个ret=$? executes with $? $?执行$? set to 0 , if it fails, then the first ret=$? 设置为0 ,如果失败,则第一个ret=$? is omitted, and the second executes. 省略,第二个执行。

Sometimes I do this: 有时我这样做:

ret=0
asd || ret=$?
echo asd exited with $ret

which works just the same and I can forget if the && or || 它的工作原理相同,我忘记了&&|| should go first. 应该先走。 And you can also do this: 您也可以这样做:

if asd; then
   ret=0
else
   ret=$?
fi
echo asd exited with $ret

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM