control-flow
return
Exits a shell function or sourced script and returns exit status N (0-255). Without N, returns the exit status of the last command executed in the function.
return [N] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| N | Exit status to return (0-255; values wrap mod 256) |
| (no flag) | Return status of last command |
| in sourced script | Exits the sourced file without exiting the shell |
| vs exit | return leaves the function; exit terminates the shell |
Examples
check() { [[ -f $1 ]] && return 0 || return 1; } Returns 0 if file exists, 1 otherwise.
load() { [[ $# -eq 0 ]] && return 2; source "$1"; } Early-return with a specific error code.
myfn() { some_cmd; return; } Bare 'return' passes through some_cmd's exit status.
[[ ${BASH_SOURCE[0]} != "$0" ]] || return 0 Guard at top of a sourced library file.
Gotcha
'return' outside a function or sourced file is an error. Exit codes are 0-255 — 'return 300' actually returns 44 (300 mod 256).
Related
source (.)
Executes FILE in the CURRENT shell (no subshell), so variables, functions, and aliases defined in it persist. Contrast with 'bash file' which runs in a child process — its side effects vanish when it exits.
local
Declares a variable scoped to the current function, hiding any global of the same name during the function's execution. Accepts the same attribute flags as declare (-a, -A, -i, -r, -n, ...).
if / then / elif / else / fi
Conditional branching based on the exit status of a command (0 = true, non-zero = false). Runs the then-branch when the tested command succeeds; supports optional elif and else clauses and must be terminated with fi.
for ... in / for ((;;))
Iterates a variable over a word list, glob, or command substitution; the C-style form iterates using arithmetic. Executes the body once per iteration and exits with the status of the last command run.
while / until / do / done
Repeats the body while (or until) the condition command exits 0. 'while' loops while the condition succeeds; 'until' is the inverse and is idiomatic for polling until a service becomes ready.