【问题标题】:How to exit a function in bash如何在bash中退出函数
【发布时间】:2013-08-05 05:20:31
【问题描述】:

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

例子

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

【问题讨论】:

  • 查看this answer 以获得干净、安静和简单的退出方式。

标签: bash function exit


【解决方案1】:

用途:

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.

【讨论】:

  • 请注意,如果您在脚本顶部设置了set -e,并且您的return 1 或除0 之外的任何其他数字,您的整个脚本都将退出。
  • @YevgeniyBrikman 仅当函数中的错误出乎意料时才成立。如果使用例如调用函数|| 那么有可能返回一个非零代码并且仍然让脚本继续执行。
  • @DanPassaro 是的,肯定有可能的解决方案,但我只想指出需要特别注意set -e 并返回非零值,因为这让我感到意外过去。
【解决方案2】:

使用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 0 退出了我的终端。 Return 1 在我的情况下按预期工作。
【解决方案3】:

如果你想从 outer 函数返回但没有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。

【讨论】:

  • 你能解释一下内部函数fail,冒号在这里是做什么的?
  • : 是一个内置的 bash 运算符,它是一个“无操作”。它对表达式求值,但不对它做任何事情。我正在使用它来进行变量替换,如果未定义变量,它将失败,这显然不是。
  • 谢谢。我可以将表达式替换为其他表达式来检查do-something-complex 的输入参数吗? checkPara () { if [ $1 -lt $2 ];然后回显 $3;菲; } do-something-complex() { checkPara $# 1 "这里有一些消息警告用户如何使用该功能。" echo "yes" } 我会 do-something-complex 向用户显示一些消息,如果没有参数提供给函数,则立即返回。
  • 这个答案非常缺乏解释,即使在回复“你能解释一下......”之后也是如此。就好像艾略特不想透露他的“把戏”一样。
  • 还有什么要解释的?这是一个变量替换,我们希望变量被定义。
猜你喜欢
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 2011-05-24
相关资源
最近更新 更多