December 6, 2026

Bash Functions: Return Values, local Variables and the $? Trap

A row of small toolboxes on a workshop shelf with one open

A Bash function told to return 300 hands back 44. One told to return 256 hands back 0, which every if statement in the script will read as success. That isn’t a bug in Bash. A function’s return value in Bash was never meant to carry data; it carries an exit status, and exit statuses are eight bits wide. Most confusion about Bash functions comes from expecting them to behave like functions in Python or JavaScript. They behave like small commands instead. Every example below was run in GNU Bash 5.2.21, and the output shown is exactly what it printed.

Video: You Suck at Programming on YouTube

A function is a small command

Two ways to define one

The Bash manual’s page on shell functions lists two forms: fname () compound-command and function fname [()] compound-command. The first is the portable one, and the one most scripts use:

greet() {
  echo "Hello, $1"
}
greet Ada      # Hello, Ada

Arguments arrive like a script’s arguments

Inside a function, $1, $2 and the rest are the function’s own arguments, $# is their count, and "$@" is all of them with quoting preserved:

show() {
  echo "count=$# first=$1 all=[$*]"
  for a in "$@"; do printf '<%s>' "$a"; done; echo
}
show one "two words" three
count=3 first=one all=[one two words three]
<one><two words><three>

Three arguments, and “two words” stayed one argument because the loop used the quoted "$@".

Vintage counter with mechanical digits in a workshop

What return really returns

A status, not a value

The manual says that without an explicit return, “the exit status of a function is the exit status of the last command executed in the body.” That makes yes-or-no functions almost free:

is_even() { (( $1 % 2 == 0 )); }
if is_even 4; then echo "4 is even"; fi    # 4 is even
is_even 7; echo "status for 7: $?"         # status for 7: 1

The arithmetic test is the last command, its status becomes the function’s status, and if reads it directly. Zero means true. Anything else means false.

Eight bits and no more

The return builtin’s entry in the manual is precise: “If n is supplied, the return value is its least significant 8 bits.” The test run shows what that means:

Command $? afterward
return 255 255
return 256 0
return 300 44
return -1 255

300 minus 256 is 44. 256 wraps to 0, which a caller will read as success. A function that tries to return a count, a port number or a price through return will silently produce garbage the moment the number passes 255. The fix is to stop using return for data at all.

Getting real data out

Print it and capture it

The standard pattern is to echo the result and capture it with command substitution:

add() { echo $(( $1 + $2 )); }
sum=$(add 2 3)
echo "sum=$sum"     # sum=5

This works for strings, large numbers and multi-line output. Its one rule: the function must print nothing else to standard output, or the extra text ends up in the variable. Diagnostic messages belong on standard error, with echo "warning" >&2.

The hidden cost: a subshell

$( … ) runs the function in a subshell, a separate copy of the shell. Anything the function changes there disappears when it ends:

n=0
inc_echo() { n=$((n+1)); echo "$n"; }
v=$(inc_echo); echo "captured $v, n is still $n"
inc_echo >/dev/null; echo "called directly, n is $n"
captured 1, n is still 0
called directly, n is 1

Captured, the function’s change to n was lost. Called directly, it stuck. A function that both prints a result and updates a counter needs one of the next two approaches.

Write into a variable the caller names

Modern Bash has a cleaner option, namerefs. The builtins page describes declare -n as “making it a name reference to another variable”; every assignment to the reference lands on the variable it points to. local -n does the same inside a function:

set_result() { local -n ref=$1; ref="hello from function"; }
set_result answer
echo "answer=$answer"     # answer=hello from function

No subshell, no capture, and the caller picks the variable name. It works for arrays too:

split_words() { local -n arr_out=$1; read -ra arr_out <<< "$2"; }
split_words parts "alpha beta gamma"
echo "${#parts[@]} -> ${parts[1]}"    # 3 -> beta

The manual adds one restriction: the nameref attribute itself “cannot be applied to array variables.” The reference has to be a plain name, even when the thing it points to is an array, as here.

A group of Russian nesting dolls sitting on a table

Variables leak unless declared local

Every variable is global by default

Assign a variable inside a function and it changes the caller’s copy:

counter=100
bump() { counter=1; }
bump; echo "counter after bump: $counter"              # 1

counter=100
bump_local() { local counter=1; }
bump_local; echo "counter after bump_local: $counter"  # 100

The manual’s description of local is that it gives the variable “a visible scope restricted to that function and its children.” Every variable a function uses for its own work should be declared local. Loop counters named i are the classic casualty: two functions both using a global i will corrupt each other’s loops.

Local isn’t private: dynamic scope

“Its children” matters. Bash, the functions page says, “uses dynamic scoping to control a variable’s visibility within functions.” A function called from another function sees the caller’s locals:

outer() { local x="from outer"; inner; }
inner() { echo "inner sees: ${x:-unset}"; }
x="global"
outer     # inner sees: from outer
inner     # inner sees: global

inner read x from whoever called it. Python and JavaScript use lexical scope, where a function sees variables based on where it was written. Bash looks up the call stack at run time. It occasionally helps and more often surprises.

The local trap that hides failures

local has its own exit status

This one bites experienced scripters too:

f1() { local out=$(false); echo "local+assign status: $?"; }
f1     # local+assign status: 0

f2() { local out; out=$(false); echo "separate assign status: $?"; }
f2     # separate assign status: 1

The command inside failed in both. In f1, $? reported success anyway. The reason is in the builtin’s documentation: “The return status is zero unless local is used outside a function, an invalid name is supplied, or name is a readonly variable.” local out=$(false) is one command, local, and local succeeded. The failure of false is swallowed.

Why it matters with set -e

Scripts running under set -e or checking $? after local x=$(some_command) will miss errors entirely. A download that failed, a file that wasn’t found, a parser that crashed: the script carries on with an empty variable. The fix is the f2 pattern. Declare on one line and assign on the next, then the assignment’s status is the command’s status.

The same masking applies to export var=$(cmd) and declare var=$(cmd). Tested the same way with false inside, both reported status 0. All three are commands with their own status.

Close-up of an old control panel with indicator lights

Debugging and limits

Finding the current function

Bash keeps a call stack in the FUNCNAME array. Element 0 is the current function, element 1 its caller:

whoami_fn() { echo "in ${FUNCNAME[0]} called from ${FUNCNAME[1]:-main}"; }
caller_fn() { whoami_fn; }
caller_fn     # in whoami_fn called from caller_fn

That makes for useful log lines in long scripts, especially inside a shared error handler.

Runaway recursion

Bash allows recursion with no limit by default, so an accidental infinite loop of calls can grind a machine until memory runs out. The manual describes a guard: “The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting level.” With FUNCNEST=5, a function that calls itself forever stopped with:

rec: maximum function nesting level exceeded (5)

Real recursion in Bash is rare, but setting FUNCNEST in a script under development costs one line.

Restoring shell options on the way out

One more local feature from the builtins page: if the name is a single dash, local -, “the set of shell options is made local to the function,” and options changed with set are restored when it returns. A function can turn on set -x tracing for itself without leaving it on for the rest of the script.

A function template worth copying

Putting the rules together

parse_port() {
  local -n _out=$1        # caller names the result variable
  local raw
  raw=$(grep -m1 '^port=' "$2") || return 1   # status survives
  _out=${raw#port=}
}

if parse_port port config.ini; then
  echo "port is $port"
else
  echo "no port found" >&2
fi

Every rule from above is here. The return status says success or failure. The data travels through a nameref, so a port above 255 survives intact. Variables are local. The assignment that can fail is separate from its local declaration, so the failure reaches return 1. And the error message goes to standard error.

Run against a config file containing port=8443, it printed port is 8443. Pointed at a missing file, grep’s error went to standard error, the function returned 1 and the script printed no port found.

The underscore in _out is a habit worth keeping. A test where the nameref and the caller’s variable were both called out printed warning: out: circular name reference three times. A prefix makes that collision unlikely.

Sources

  • GNU Bash Reference Manual, “Shell Functions”: https://www.gnu.org/software/bash/manual/html_node/Shell-Functions.html
  • GNU Bash Reference Manual, “Bourne Shell Builtins” (return): https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html
  • GNU Bash Reference Manual, “Bash Builtin Commands” (local, declare -n): https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *