Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The return statement is a POSIX-compliant shell builtin used exclusively within a function or a sourced script to terminate execution and pass an integer exit status back to the calling context. Unlike return statements in high-level programming languages, Bash’s return does not pass data or objects; it strictly sets the $? special parameter to indicate success or failure.

Syntax

return [n]
  • n: An optional non-negative integer representing the exit status.

Mechanics and Behavior

  • Integer Evaluation and Modulo Operation: The argument n must be a non-negative numeric value. The resulting exit status is strictly constrained to an 8-bit unsigned integer (0 to 255). If a non-negative integer greater than 255 is provided, Bash applies a modulo 256 operation (e.g., return 256 yields an exit status of 0, and return 257 yields 1).
  • Invalid Arguments: Bash does not support negative integers for the return builtin. Executing return -1 causes Bash to interpret the - as an option flag, resulting in a usage error (bash: return: -1: invalid option) and an exit status of 2. Bypassing option parsing with return -- -1 results in a type error (bash: return: -1: numeric argument required) and an exit status of 255.
  • Omitted Argument: If n is omitted, the return statement defaults to the exit status of the last command executed within the function or sourced script prior to the return call.
  • Execution Termination: Upon encountering return, the shell immediately halts execution of the current function or sourced script, pops the current execution context off the call stack, and resumes execution at the next command in the calling scope.

Scope Limitations

The return builtin is context-dependent. It is only valid in two scenarios:
  1. Inside a defined function.
  2. Inside a script being executed via the source or . commands.
If return is invoked in the main execution flow of a standard script (not sourced), Bash prints an error message (bash: return: can only \return’ from a function or sourced script) and yields an exit status of 1`. It does not halt script execution; the shell continues processing the next command in the script.

State Retrieval

Because return does not output to stdout, the calling context must capture the exit status using the $? special parameter immediately after the function invocation.
my_function
exit_status=$?
Any intermediate command executed between the function call and the evaluation of $? will overwrite the $? parameter with its own exit status.
Master Bash with Deep Grasping Methodology!Learn More