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

时间:2015-09-18 10:15:53

标签: bash

显然可以使用 $?,但脚本包含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**

1 个答案:

答案 0 :(得分:1)

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

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

行为记录在man bash下的set

  

如果命令,shell不会退出                         失败是紧随while或之后的命令列表的一部分                         until关键字,是ifelif保留之后的部分测试                         单词,在&&||列表中执行的任何命令的一部分,除了最后&&||之后的命令,管道中的任何命令但是                         最后,或者如果命令的返回值被!反转。