如果您想从外部函数返回错误而不带错误,exit
可以使用以下技巧:
do-something-complex() {
# Using `return` here would only return from `fail`, not from `do-something-complex`.
# Using `exit` would close the entire shell.
# So we (ab)use a different feature. :)
fail() { : "${__fail_fast:?$1}"; }
nested-func() {
try-this || fail "This didn't work"
try-that || fail "That didn't work"
}
nested-func
}
尝试一下:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
这具有附加的好处/缺点,您可以选择关闭此功能:__fail_fast=x do-something-complex
。
请注意,这会使最外面的函数返回1。
set -e
在脚本的顶部设置了您的脚本,并且您的return 1
或除0以外的其他任何数字都已设置,则整个脚本将退出。