Ato*_*lan 72 bash function exit
如果条件为真而没有终止整个脚本,你将如何退出函数,只需在调用函数之前返回.
例
# 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
}
Run Code Online (Sandbox Code Playgroud)
moh*_*hit 96
使用:
return [n]
Run Code Online (Sandbox Code Playgroud)
从 help return
return:return [n]
Run Code Online (Sandbox Code Playgroud)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.
Nem*_*ric 16
使用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
}
Run Code Online (Sandbox Code Playgroud)
如果你想从一个有错误的外部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
}
Run Code Online (Sandbox Code Playgroud)
尝试一下:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
Run Code Online (Sandbox Code Playgroud)
这有一个额外的好处/缺点,您可以选择关闭此功能:__fail_fast=x do-something-complex。
请注意,这会导致最外面的函数返回 1。
| 归档时间: |
|
| 查看次数: |
77656 次 |
| 最近记录: |