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

← All Bash builtins · Linux commands