145

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

例子

# 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
}
4

3 回答 3

192

采用:

return [n]

help 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.
于 2013-08-04T11:12:57.297 回答
29

使用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
}
于 2013-08-04T11:12:05.713 回答
4

如果您想从带有错误的外部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。

于 2019-01-09T21:12:24.497 回答