如何在 bash 中退出函数

如果一个条件为 true 而不杀死整个脚本,那么如何退出函数,只需返回到调用函数之前。

例子

# Start script
Do scripty stuff here
Ok now lets call FUNCT
FUNCT
Here is A to come back to


function FUNCT {
if [ blah is false ]; then
exit the function and go up to A
else
keep running the function
fi
}
181994 次浏览

使用 return操作员:

function FUNCT {
if [ blah is false ]; then
return 1 # or return 0, or even you can omit the argument.
else
keep running the function
fi
}

用途:

return [n]

来自 help return

Return : return [ n ]

Return from a shell function.


Causes a function or sourced script to exit with the return value
specified by N.  If N is omitted, the return status is that of the
last command executed within the function or script.


Exit Status:
Returns N, or failure if the shell is not executing a function or script.

如果你想从 外面函数返回一个没有 exiting 的错误,你可以使用这个技巧:

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。

我的用例是运行函数,除非它已经在运行了

mkdir /tmp/nice_exit || return 0

然后在函数的末尾

rm -rf /tmp/nice_exit