Functions, local variables, and return status
- Version
- 5.3
- Review
- Draft
Summary#
A Bash function groups commands under a name and receives its own positional arguments. An ordinary function call runs in the calling shell. Use local to give a variable a binding that the function and the functions it calls can see.
Syntax#
name() {
local value="${1-}"
[[ -n $value ]] || return 2
printf '%s\n' "$value"
}
name argument
return N ends the call with status N. If execution reaches the end of the body, the last command sets the function status. Write data to standard output so callers can capture it with $(name argument).
Example#
The function prints the selected queue and leaves the caller’s variable intact. An empty argument makes it return status 2.
label='default queue'
show_queue() {
local label="${1-}"
if [[ -z $label ]]; then
return 2
fi
printf 'selected: %s\n' "$label"
}
show_queue 'overnight'
if show_queue ''; then
printf '%s\n' 'unexpected success'
else
printf 'empty label: status %d\n' "$?"
fi
printf 'outer label: %s\n' "$label"
Expected output#
selected: overnight
empty label: status 2
outer label: default queue
Common mistakes#
Use return to leave the function while letting the caller continue. Declare local result on its own before assigning result=$(produce) if you need to check produce’s status. In local result=$(produce), the local builtin supplies the status of the combined command.
Version applicability#
The definition, local, and return forms shown here, including the complete example, work on Bash 3.2.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0