Return Values and Exit Codes
Return Values and Exit Codes
A critical limitation in shell programming: return only returns an integer status code between 0 and 255. It cannot return strings or data objects!
Returning Data Strategies
# Strategy 1: stdout capture (spawns subshell)
get_hostname() {
echo "host-$(hostname -s)"
}
host=$(get_hostname)
# Strategy 2: Pass-by-reference with nameref (Bash 4.3+, zero subshell overhead!)
get_system_info() {
local -n out_ref="$1" # nameref to caller variable
out_ref="OS=Linux Kernel=$(uname -r)"
}
info=""
get_system_info info
echo "$info"