web-dev-qa-db-ja.com

bashで関数を終了する方法

スクリプト全体を殺すことなく条件が真である場合、関数を終了する前に、関数を呼び出す前に戻ります。

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

つかいます:

return [n]

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.
87
mohit

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
}
16
Nemanja Boric

exitingなしでエラーのあるouter関数から戻りたい場合は、次のトリックを使用できます。

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を返すことに注意してください。

0
Elliot Cameron