简体   繁体   English

从子 shell 中运行的命令中识别 bash 退出代码 - 使用 set -e 时

[英]Identify the bash exit code from a command run in a sub shell - when set -e is used

Obviously $?显然$? could be used, but the script contains set -e, which causes an exit as soon as a command fails可以使用,但脚本包含 set -e,这会在命令失败后立即退出

A very artifical example:一个非常人为的例子:

set -eu -o pipefail
...
# file does_not_exist does not exist
# the following would result in an immediate exit of the script
mv does_not_exist new_file
# as does the following
$(mv does_not_exist new_file)
# but this neat trick doesn't exit the script
declare -r RES=$(mv does_not_exist new_file)
# however I'd also like to get at the exit code of **mv**

You can examine $?你可以检查$? in the "or" part of the command:在命令的“或”部分:

set -e
ls /does-not-exist || echo $?
echo end

The behaviour is documented in man bash under set :该行为记录在man bashset

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or ||如果失败的命令是紧跟在whileuntil关键字之后的命令列表的一部分、在ifelif保留字之后的测试的一部分、在&&||执行的任何命令的一部分,则 shell 不会退出list except the command following the final && or ||除了最后一个&&||之后的命令之外的列表, any command in a pipeline but the last, or if the command's return value is being inverted with ! , 管道中除最后一个命令之外的任何命令,或者如果命令的返回值正在用! . .

暂无
暂无

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

相关问题 bash - 使用 set -e 时如何处理退出代码并获取命令输出 - bash - how to process exit code when using set -e and get output of command Bash:在设置“set -e”时捕获退出代码而不是中止? - Bash: Capture exit code instead of aborting, when "set -e" is set? 当“set -e”处于活动状态时,Bash 获取命令的退出状态? - Bash get exit status of command when 'set -e' is active? Bash:期望使用set -e设置不同的退出代码 - Bash: Expect different exit code with set -e 从错误上自动退出bash shell脚本:set + e似乎没有完成这项工作 - Automatic exit from bash shell script on error: set +e does not seem to do the job 鱼壳:如何退出错误(bash set -e) - Fish shell: how to exit on error (bash set -e) 我可以创建一个依赖于shell中先前执行的命令的退出代码的bash脚本吗? - Can I create a bash script that relies on the exit code from the previously executed command in my shell? 在以set -e开头的bash脚本中,我可以将退出代码设置为与第一个失败命令不同的值吗? - In a bash script that starts with set -e, can I set the exit code to a different value than the first failed command's? bash 如何将命令作为参数传递给在子 shell 中运行的 function? - How to bash pass command as an argument to function which run in sub shell? cygwin 1.7.15在外壳程序脚本中处理“ set -e”(子外壳程序中的错误导致父级退出) - cygwin 1.7.15 handling of “set -e” in shell scripts (error in sub-shell causes parent to exit)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM