bash 如何退出bash中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18042279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:00:13  来源:igfitidea点击:

How to exit a function in bash

bashfunctionexit

提问by Atomiklan

How would you exit out of a function if a condition is true without killing the whole script, just return back to before you called the function.

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

Example

例子

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

回答by mohit

Use:

用:

return [n]

From help return

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.

返回: 返回 [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.

回答by Nemanja Boric

Use returnoperator:

使用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
}

回答by Elliot Cameron

If you want to return from an outerfunction with an error without exiting you can use this trick:

如果你想从一个带有错误的外部函数返回而不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:?}"; }

  nested-func() {
      try-this || fail "This didn't work"
      try-that || fail "That didn't work"
  }
  nested-func
}

Trying it out:

尝试一下:

$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work

This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

这具有额外的好处/缺点,您可以选择关闭此功能:__fail_fast=x do-something-complex

Note that this causes the outermost function to return 1.

请注意,这会导致最外层函数返回 1。