How to exit a function in bash

BashFunctionExit

Bash Problem Overview


How would you exit out of a function if a condition is true without killing the whole script, just return back to before you called the function.

Example

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

Bash Solutions


Solution 1 - Bash

Use:

return [n]

From 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.

Solution 2 - Bash

Use return operator:

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
}

Solution 3 - Bash

If you want to return from an outer function with an error without exiting you can use this trick:

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
}

Trying it out:

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

This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

Note that this causes the outermost function to return 1.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtomiklanView Question on Stackoverflow
Solution 1 - BashmohitView Answer on Stackoverflow
Solution 2 - BashNemanja BoricView Answer on Stackoverflow
Solution 3 - BashElliot CameronView Answer on Stackoverflow