web-dev-qa-db-fra.com

Comment quitter une fonction dans bash

Comment voudriez-vous sortir d'une fonction si une condition est vraie sans tuer tout le script, revenez à avant d'appeler la fonction.

Exemple

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

Utilisation:

return [n]

De help return

retour : retour [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.
69
mohit

Utilisez l'opérateur 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
}
15
Nemanja Boric

Si vous voulez revenir d'une fonction outer sans exiting, vous pouvez utiliser cette astuce:

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

L'essayer:

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

Cela a l'avantage supplémentaire/inconvénient que vous pouvez éventuellement désactiver cette fonctionnalité: __fail_fast=x do-something-complex.

Notez que cela provoque le retour de la fonction la plus externe 1.

0
Elliot Cameron