196

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

5 Answers 5

267

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.
3
  • 56
    Note that if you have set -e set at the top of your script and your return 1 or any other number besides 0, your entire script will exit. Commented May 6, 2016 at 10:53
  • 2
    @YevgeniyBrikman that's only true if the error in the function is unexpected. If the function is called using e.g. || then it's possible to return a nonzero code and still have the script continue to execute. Commented Jul 11, 2019 at 20:32
  • 4
    @DanPassaro Yup, there are definitely solutions possible, but I just wanted to call out that extra care needs to be taken with set -e and returning non-zero values, as that caught me by surprise in the past. Commented Jul 12, 2019 at 21:19
40

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
}
2
  • Return 0 exited my terminal. Return 1 works as expected in my case.
    – progonkpa
    Commented Oct 8, 2021 at 12:48
  • 1
    @progonka, 0 is success and 1 is failure, so that wouldn't happen unless you had other code branching on the return value. Commented Jun 8 at 20:03
8

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.

10
  • 1
    Could you explain more on the inner function fail, what is the colon doing here?
    – brook hong
    Commented Apr 25, 2019 at 2:38
  • 1
    The : is a built-in bash operator that is a "no-op". It evaluates the expression but doesn't do anything with it. I'm using it to do variable substitution that will fail if the variable isn't defined, which it obviously isn't. Commented Apr 25, 2019 at 3:08
  • Thanks. Could I replace the expression to some other expression to check the input parameter of do-something-complex? <code> checkPara () { if [ $1 -lt $2 ]; then echo $3; fi; } do-something-complex() { checkPara $# 1 "Some message here to warn user how to use the function." echo "yes" } </code> I would do-something-complex show user some message and return immediately if there is no parameter fed to the function.
    – brook hong
    Commented Apr 25, 2019 at 5:10
  • 1
    This answer is sorely lacking in explanation, even after the response to "Could you explain...". It's as if Elliot doesn't want to reveal his "trick".
    – jdunk
    Commented Jun 13, 2021 at 14:35
  • 1
    What's left to explain? It's a variable substitution where we expect the variable to not be defined. Commented Jun 14, 2021 at 15:26
0

I found the above examples incomplete. And tbh confusing.

function test() { [[ 5 -eq 5 ]] && return 0 || return 1 ; } ; test ; echo $?

function test() { [[ 5 -eq 3 ]] && return 0 || return 1 ; } ; test ; echo $?

will print

0

1

2
  • You're merging POSIX and legacy ksh function syntax in a way that's incompatible with both POSIX and legacy ksh. Use funcname() without function to have modern POSIX syntax, or function funcname without () for 80s ksh syntax. Commented Jun 8 at 20:04
  • That said, you'd get exactly the same outcome as the first from test() { [[ 5 -eq 5 ]]; }, or the second from test() { ! [[ 5 -eq 5 ]]; } -- all the && and || in this answer is completely redundant. (The default return value of a function is always $?; that's also true when you call return with no arguments) Commented Jun 8 at 20:07
-1

My use case is to run the function unless it's already running. I'm doing

mkdir /tmp/nice_exit || return 0

And then at the end of the function

rm -rf /tmp/nice_exit
2
  • You might want to use rmdir instead of rm -rf. Your function will also never run anymore if an unexpected error or oversight causes it to stop without deleting that directory (function returns, program or system exits/crashes/is powered off...) For these reasons you might want to use a lock file with flock(1) instead. Commented Nov 3, 2022 at 12:36
  • @FrenchMasterSword Yeah, it's a function that's running when a container is exiting. So I don't think all that applies. Happy to solve any issues that come up with not running, just always want to make sure it doesn't run again at the same time.
    – nroose
    Commented Nov 3, 2022 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.