如何将函数作为“测试命令”运行并在失败时执行操作,同时仍然在发生错误时立即中止该函数? 考虑以下脚本
#!/bin/bash -e
function foo() {
echo Entering foo
false
echo Should not reach this line
}
foo || echo I want to see this line on failure in foo
foo
我得到的输出是
Entering foo
Should not reach this line
Entering foo
虽然我想得到
Entering foo
I want to see this line on failure in foo
Entering foo
我想我正在寻找的是一种将函数标记为未测试命令的方法。根据 bash 手册页
-e errexit
Exit immediately if any untested command fails in non-interactive
mode. The exit status of a command is considered to be explicitly
tested if the command is part of the list used to control an if,
elif, while, or until; if the command is the left hand operand of
an “&&” or “||” operator; or if the command is a pipeline preceded
by the ! operator. If a shell function is executed and its exit
status is explicitly tested, all commands of the function are con‐
sidered to be tested as well.
编辑 预期的输出是错误的。为清楚起见对其进行了编辑
最佳答案
set -e
在第一次调用 foo
时被禁用,因为它位于 ||
的左侧。
此外,你永远不会看到输出的 I want to see this ...
字符串,除非 foo
中的最后一个 echo
不知何故失败(是 foo
中的最后一个 echo
决定函数的退出状态)。
foo() {
echo Entering foo
false && echo Should not reach this line
}
foo || echo I want to see this line on failure in foo
foo
以上输出(带或不带set -x
)
Entering foo
I want to see this line on failure in foo
Entering foo
现在 false
是 foo
中最后执行的语句。
关于linux - Bash 函数忽略 set -e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50785352/