Skip to content
Tutorials Center
My learning

Topics

Linux Command Reference ยท Shell Builtins

Linux return and exit commands

Reference for the Bash return and exit builtins: end functions and scripts with a status code, the default status, subshell behavior and exit status ranges.

exit ends the current shell (usually the whole script) and passes a status code to whoever started it. return ends only the current function, or a script run with source, and hands a status back to the caller. Both take an optional number from 0 to 255; 0 means success and anything else signals a kind of failure.

If you omit the number, both use the status of the last command that ran. That default is convenient and a common source of surprises, which is why explicit codes are better.

Terminal
exit 0          # whole script, success
return 1        # leave the function, failure

Try it

Bash return in functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash exit in scripts and subshells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Syntax

Terminal
return [N]
exit [N]
Name Description
N Exit status, an integer taken modulo 256. Omitted: the status of the last executed command.

Returns: neither returns to its caller in the usual sense. exit terminates the shell; return resumes the caller with $? set to N.

Errors and edge cases: return outside a function or a sourced script prints an error and fails. A non-numeric argument gives an error and status 2 (Bash) in most versions.

Usage notes

  • Conventions. 0 success, 1 general failure, 2 misuse of a command, 126 found but not executable, 127 command not found, 128+N killed by signal N (so 130 is Ctrl-C, 143 is SIGTERM).
  • Functions return status, not data. To pass a string or number out of a function, echo it and capture with $(...), or set a global variable.
  • exit in a function exits the script. That is often what you want in a die() helper, but it surprises people who expect return.
  • Subshells swallow exit. A pipeline's non-last stages and $(...) run in subshells; an exit there stops the subshell only.
  • EXIT traps run after exit. Put cleanup in one, as described in trap.
  • Sourced scripts. return in a file loaded by source stops that file and gives control back; exit would end your interactive shell.
  • With set -e, a failing command ends the script as if by exit; see set.
  • Check the status at once. $? is replaced by every command, including echo. Save it (rc=$?) before using it twice.