How to exit a function in bash

Atomiklan picture Atomiklan · Aug 4, 2013 · Viewed 110.3k times · Source

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
}

Answer

mohit picture mohit · Aug 4, 2013

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.