繁体   English   中英

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

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

显然$? 可以使用,但脚本包含 set -e,这会在命令失败后立即退出

一个非常人为的例子:

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**

你可以检查$? 在命令的“或”部分:

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

该行为记录在man bashset

如果失败的命令是紧跟在whileuntil关键字之后的命令列表的一部分、在ifelif保留字之后的测试的一部分、在&&||执行的任何命令的一部分,则 shell 不会退出除了最后一个&&||之后的命令之外的列表 , 管道中除最后一个命令之外的任何命令,或者如果命令的返回值正在用! .

暂无
暂无

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

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