如何在bash中退出函数

时间:2013-08-04 11:10:10

标签: 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
}

3 个答案:

答案 0 :(得分:79)

使用:

return [n]

来自help 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.

答案 1 :(得分: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
}

答案 2 :(得分:0)

如果您想在没有错误exit的情况下从外部函数返回错误,可以使用以下技巧:

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。