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.
exit 0 # whole script, success return 1 # leave the function, failure
Try it
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.
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
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.
0success,1general failure,2misuse of a command,126found but not executable,127command not found,128+Nkilled by signalN(so130is Ctrl-C,143isSIGTERM). - Functions return status, not data. To pass a string or number out of a function,
echoit and capture with$(...), or set a global variable. exitin a function exits the script. That is often what you want in adie()helper, but it surprises people who expectreturn.- Subshells swallow
exit. A pipeline's non-last stages and$(...)run in subshells; anexitthere stops the subshell only. - EXIT traps run after
exit. Put cleanup in one, as described intrap. - Sourced scripts.
returnin a file loaded bysourcestops that file and gives control back;exitwould end your interactive shell. - With
set -e, a failing command ends the script as if byexit; seeset. - Check the status at once.
$?is replaced by every command, includingecho. Save it (rc=$?) before using it twice.
Related
trap,trueandfalse,source,exec, Exit status- Lessons: Exit codes and errors, Functions, First script