set -e(或以脚本开头#!/bin/sh -e)对于在出现问题时自动轰炸非常有用.它使我不必错误地检查可能失败的每个命令.
如何在函数内获得相应的内容?
例如,我有以下脚本在出错时立即退出并出现错误退出状态:
#!/bin/sh -e
echo "the following command could fail:"
false
echo "this is after the command that fails"
Run Code Online (Sandbox Code Playgroud)
输出如预期:
the following command could fail:
Run Code Online (Sandbox Code Playgroud)
现在我想把它包装成一个函数:
#!/bin/sh -e
my_function() {
echo "the following command could fail:"
false
echo "this is after the command that fails"
}
if ! my_function; then
echo "dealing with the problem"
fi
echo "run this all the time regardless of the success of my_function"
Run Code Online (Sandbox Code Playgroud)
预期产量:
the following command could fail: …Run Code Online (Sandbox Code Playgroud) 我试图在循环中调用一个函数,并在它抛出时优雅地处理和继续。
如果我省略|| handle_error它只会像人们期望的那样停止整个脚本。
如果我离开|| handle_error那里,它将foo is fine在错误发生后打印并且根本不会执行handle_error。这也是预期的行为,这就是它的工作方式。
#!/bin/bash
set -e
things=(foo bar)
function do_something {
echo "param: $1"
# just throw on first loop run
# this statement is just a way to selectively throw
# not part of a real use case scenario where the command(s)
# may or may not throw
if [[ $1 == "foo" ]]; then
throw_error
fi
# this line should not be executed when $1 is …Run Code Online (Sandbox Code Playgroud) 注意:如果您正在寻找一种解决方法,因为set -e在函数中不起作用,请转到函数中的"set -e".这个问题是为什么它不能按预期工作.
当在GNU bash上运行以下版本时,版本4.1.5(1) - 释放:
set -ex
PS4=' ${FUNCNAME[0]}: $LINENO: '
function f() {
set -e
false
echo $@
}
! f why does it display ? It should stop because of -e
f
Run Code Online (Sandbox Code Playgroud)
它显示
: 11: f why does it display '?' It should stop because of -e
f: 6: set -e
f: 7: false
f: 8: echo why does it display '?' It should stop because of -e
why …Run Code Online (Sandbox Code Playgroud)