如何在bash中退出函数

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]

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.
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果你在脚本的顶部设置了`set -e`并且你的`return 1`或除了0之外的任何其他数字,你的整个脚本将退出. (13认同)
  • @YevgeniyBrikman 仅当函数中的错误是意外的时才是正确的。如果使用例如“||”调用该函数,则可以返回非零代码并且仍然让脚本继续执行。 (2认同)
  • @DanPassaro 是的,肯定有可能的解决方案,但我只是想指出需要格外小心“set -e”并返回非零值,因为这在过去让我感到惊讶。 (2认同)

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)


Ell*_*ron 8

如果你想从一个有错误的外部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。