如果您想从带有错误的外部exit
函数返回而没有ing 您可以使用此技巧:
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。