return
Exit function, script, or subshell
TLDR
Exit a function prematurely
Specify the function's return value
SYNOPSIS
return [n]
PARAMETERS
n
An optional integer value between 0 and 255. This value will be used as the exit status of the function or script. If omitted, the exit status is that of the last executed command within the function or script.
DESCRIPTION
The return command is used to exit a function or script. It allows a function or script to send a specific exit status back to the calling process. If used outside of a function or script, it exits the current shell (similar to `exit`). Without an argument, return exits the function or script with the exit status of the last executed command. The exit status is a numerical value between 0 and 255 (inclusive), where 0 generally indicates success, and non-zero values indicate failure or errors. This command offers a mechanism for functions and scripts to communicate completion status, success, or failure to the calling program, facilitating more robust and controlled scripting.
CAVEATS
Exit status values are limited to the range of 0-255. Attempting to return a value outside this range may result in unexpected behavior due to modulo 256 arithmetic. The return command can behave like exit when it's used outside of function body or shell script.
EXIT STATUS CODES
Exit status codes are essential for inter-process communication. By convention, 0 indicates successful completion. Non-zero values typically represent different types of errors or failures. The specific meaning of non-zero values is application-dependent and should be documented for each script or program.
When a shell script calls another shell script, the calling script can determine the success or failure of the called script by inspecting its exit status.
RETURN IN FUNCTIONS
Within a function, return terminates the execution of the function and returns control to the caller. It can also pass a status code that the calling script can examine. If return is not used in a function, execution continues until the end of the function definition.
HISTORY
The return command has been a standard feature in most shells since their early implementations. Its purpose is to provide a way for functions and shell scripts to signal success or failure in a structured manner, improving the reliability of shell scripting. POSIX standardizes the return command and its basic functionality.