Подтвердить что ты не робот

Как выйти из функции в bash

Как вы выходите из функции, если условие истинно, не убивая всего script, просто вернитесь назад, прежде чем вы вызовете функцию.

Пример

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

Ответ 1

Использование:

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.

Ответ 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
}

Ответ 3

Если вы хотите вернуться из внешней функции без 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}"; }

  try-this || fail "This didn't work"
  try-that || fail "That didn't work"
}

Опробовать это:

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

Это имеет дополнительное преимущество/недостаток, который вы можете по желанию отключить эту функцию: __fail_fast=x do-something-complex.

Обратите внимание, что это приводит к тому, что самая внешняя функция возвращает 1.