Local Scope, Namerefs and Recursion

Local Scope, Namerefs and Recursion in Bash: --- On a large construction site there is a standing rulebook in the site office -- the permanent notices that…


The Analogy: The Construction Site's Chain of Site Notices

On a large construction site there is a standing rulebook in the site office -- the permanent notices that apply to everyone all day: the speed limit on the access road, the mandatory hard-hat zones. Everyone works to these unless told otherwise. In the shell, this permanent board is the global variable: set once, visible everywhere, in effect until someone changes it. When a subcontractor reads "hard hats required" off the board, they are reading the global.

Now a foreman takes charge of a particular task -- pouring a concrete slab in one corner -- and for the duration of that task he clips a temporary notice over the standing one: "this bay, no vibration for two hours". That temporary notice is a local variable. Here is the crucial and surprising part of how Bash works: any worker the foreman calls in to help during his task reads the temporary notice, not the standing rule, because they are working underneath his authority for that stretch. When the foreman finishes and unclips his notice, the standing rule shows through again. This is dynamic scope: a local in one function is visible to every function it calls, for as long as that call lasts -- which is different from most programming languages, where a helper would see only the rules written where it was defined, not where it was called from.

The site also uses forwarding notices. Instead of writing a measurement on a board directly, a notice might read "for the actual reading, see Gauge 12". Anyone who consults that notice is redirected to Gauge 12, and anyone who writes an update "onto" that notice is really updating Gauge 12. In Bash this forwarding notice is a nameref, declared with local -n: the variable does not hold a value of its own, it holds the name of another variable, and every read and write passes straight through to the target. This is how a Bash function can be handed the name of a caller's variable and fill it in directly -- the standard way to return a value, or several values, without the cost and isolation of a subshell.

The failure mode is a foreman who forgets to clip his own notice and instead scrawls his temporary instruction directly onto the standing rulebook. His change does not come down when his task ends; it lingers and misleads the next crew, who assume the board still shows the site-wide rule. That is the missing-local bug: a function that assigns a variable without declaring it local silently overwrites a global that the rest of the script depends on. The forwarding notices have their own hazard too -- a notice that points at a gauge which points back at the first notice sends a reader in circles, exactly the "circular name reference" a nameref raises when its target name collides with its own.


Syntax or Core Structure

The local keyword confines a variable to a function call. Bash uses dynamic scope, which means a local is visible not only in the function that declares it but in every function called from within it, for the duration of the call. This example shows the same helper seeing different values depending on who called it.

#!/usr/bin/env bash
inner() { echo "  inner sees msg=$msg"; }
outer() {
  local msg="from outer"
  echo "outer set msg"
  inner
}
msg="global"
echo "before: msg=$msg"
outer
echo "after: msg=$msg"
inner

Output:

before: msg=global
outer set msg
  inner sees msg=from outer
after: msg=global
  inner sees msg=global

The global msg starts as global. When outer runs, it declares local msg="from outer" and then calls inner. Because scope is dynamic, inner sees outer's local value and prints from outer -- even though inner never mentions outer and was defined completely separately. Once outer returns, its local is discarded and the global reappears, so the line after the call prints global again. The final call to inner at the top level, outside any function that shadowed msg, sees the global global. This dynamic visibility is powerful but must be understood: a helper's behaviour can depend on a local set by whoever called it.


Technical Depth: Namerefs, the Exit-Status Trap, and Recursion

Scope and reference constructs

Four constructs carry this lesson. The nameref is the one most people have never met, and it is the key to returning values cleanly.

ConstructEffect
local varconfines var to this call and its callees, dynamic scope
local -n ref=nameref becomes an alias for the variable called name
local var then var=cmdseparates declaration so the assignment exit status shows
local var=cmdone step, but local always returns success, masking cmd

Namerefs as output parameters

A nameref is declared with local -n and holds the name of another variable; reads and writes pass through to that target. This lets a function write a result into a variable the caller names, the idiomatic way to return data without a command-substitution subshell.

#!/usr/bin/env bash
double() {
  local -n out=$1
  local value=$2
  out=$(( value * 2 ))
}
double result 21
echo "result=$result"
double answer 50
echo "answer=$answer"

Output:

result=42
answer=100

The call double result 21 passes the string result as $1. Inside, local -n out=$1 makes out an alias for the caller's result variable, so out=$(( value * 2 )) writes 42 straight into result -- no echo, no capture, no subshell. The second call fills a different variable, answer, with 100. This pattern shines when a function must return several values at once: it takes several names and fills each, which command substitution cannot do because a subshell can only hand back a single stream of text.

The exit-status trap

Combining local with a command substitution on one line hides the command's exit status, because the status you see afterward is local's own, which is always zero.

#!/usr/bin/env bash
fails() { return 3; }
badcheck()  { local out=$(fails); echo "  combined: exit seen as $?"; }
goodcheck() { local out; out=$(fails); echo "  separated: exit seen as $?"; }
badcheck
goodcheck

Output:

  combined: exit seen as 0
  separated: exit seen as 3

In badcheck, local out=$(fails) runs fails (which returns 3) but the exit status recorded is that of the local builtin, which succeeds, so $? reads 0 and the real failure is lost. In goodcheck, the declaration and the assignment are separate statements, so after out=$(fails) the $? correctly reflects fails's status of 3. Whenever you must check the exit status of a command whose output you are capturing into a local, declare the variable first and assign on its own line.

Recursion writing through a nameref

Recursion and namerefs combine cleanly: a recursive function can accumulate into a caller's variable through a nameref, avoiding a subshell at every level.

#!/usr/bin/env bash
sum_to() {
  local -n acc=$1
  local n=$2
  (( n <= 0 )) && return
  acc=$(( acc + n ))
  sum_to "$1" $(( n - 1 ))
}
total=0; sum_to total 5;  echo "sum 1..5 = $total"
total=0; sum_to total 10; echo "sum 1..10 = $total"

Output:

sum 1..5 = 15
sum 1..10 = 55

Each level aliases the caller's total through acc, adds the current n, and recurses with n - 1 until the base case at zero. The sum from 1 to 5 is 15 and from 1 to 10 is 55. Note that the nameref target name, total, is passed down unchanged as $1 at every level, so all levels write to the same variable -- the accumulator lives in the caller, not in any single stack frame, which is exactly why the final value survives after the recursion unwinds.


Real World Example: A Statistics Function That Returns Four Values

The clearest payoff of namerefs is returning several values at once. This stats function takes the names of four caller variables plus a list of numbers, and fills in the count, sum, minimum, and maximum -- something command substitution cannot do in one call, because a subshell can only return a single text stream.

#!/usr/bin/env bash
set -u

stats() {
  local -n _n=$1 _sum=$2 _min=$3 _max=$4
  shift 4
  _n=0; _sum=0
  local first=1 x
  for x in "$@"; do
    _sum=$(( _sum + x ))
    _n=$(( _n + 1 ))
    if (( first )); then
      _min=$x; _max=$x; first=0
    else
      (( x < _min )) && _min=$x
      (( x > _max )) && _max=$x
    fi
  done
}

count=0 total=0 lo=0 hi=0
stats count total lo hi 42 17 99 8 55 23
echo "count = $count"
echo "sum   = $total"
echo "min   = $lo"
echo "max   = $hi"
avg=$(( total / count ))
echo "avg   = $avg (integer)"

Output:

count = 6
sum   = 244
min   = 8
max   = 99
avg   = 40 (integer)

Trace the fill. The four namerefs _n, _sum, _min, _max alias the caller's count, total, lo, and hi. After shift 4 removes the four names, $@ is the six numbers. The loop sums them to 244, counts 6, and tracks the running minimum (8) and maximum (99), writing each straight into the caller's variables through the aliases. Back in the caller, avg divides 244 by 6 with integer arithmetic, giving 40. One function call returned four distinct values, cleanly, with no subshell and no global-clobbering.

The design carries three real hazards. First and most nameref-specific: if a caller happens to name one of its variables the same as an internal nameref name -- calling stats _sum ... -- Bash detects that the alias would point at itself and floods standard error with "circular name reference" warnings, and the result is unreliable; the leading underscores make a collision less likely but cannot rule it out, which is the fundamental fragility of namerefs. Second, the average is integer-only: 244 divided by 6 is really 40.67, but the code prints 40, so any caller needing a true mean must scale or use a decimal tool. Third, the function does no validation: shift 4 assumes at least four arguments and errors otherwise, and a non-numeric value in the list makes the arithmetic fail mid-loop, leaving the output variables half-filled -- a robust version would check the argument count and validate each number before accumulating.


Common Mistakes

  1. Assuming lexical scope. Bash uses dynamic scope, so a helper function sees the locals of whoever called it, not the variables where it was defined. Code ported from a lexically scoped language can behave unexpectedly when a helper picks up a caller's local of the same name.
  1. Masking exit status with local var=cmd. local out=$(cmd) records the exit status of local, which is always zero, hiding cmd's real status. When you need to test the command's result, declare the variable first and assign on a separate line.
  1. Colliding a nameref name with a caller variable. If the caller's variable has the same name as the function's nameref, Bash raises a circular-reference error. Prefix internal nameref names with an underscore or another convention to reduce the chance of collision.
  1. Forgetting local on a loop counter or temp. A plain i or tmp assigned inside a function is global and clobbers any caller variable of that name. Because of dynamic scope this can also disturb a caller further up the chain. Declare every internal variable local.
  1. Expecting a local to persist after the function returns. A local exists only for the duration of the call; once the function returns, the variable is gone (or the shadowed global reappears). Values that must outlive the call have to be returned through a nameref, echoed, or written to a global deliberately.
  1. Using a nameref to a nonexistent or unset name. A nameref pointing at a name that is never set reads as empty, and typos in the passed name fail silently rather than erroring. Validate that the caller passed a real variable name when it matters.
  1. Relying on namerefs in old Bash. Namerefs require Bash 4.3 or newer. Scripts that must run on very old systems, or on a default macOS Bash 3.2, cannot use local -n and must fall back to echoing values or using eval carefully.
  1. Declaring a variable local outside a function. local is only valid inside a function; using it at the top level of a script is an error. Top-level variables are global by nature, so no local is needed or allowed there.
  1. Assuming recursion is cheap. Even with namerefs avoiding per-level subshells, deep recursion consumes shell stack and is slow compared to a loop. Bash has no tail-call optimization, so convert hot or deep recursion to iteration with an explicit accumulator.

Best Practices

  • Declare every function-internal variable local. This is the foundational discipline. It confines each variable to its call, prevents clobbering globals, and, given dynamic scope, keeps helpers from accidentally reading a caller's stray value.
  • Return multiple values through namerefs. When a function must produce more than one result, take the caller's variable names and fill them through local -n aliases. It avoids the single-stream limit of command substitution and needs no subshell.
  • Separate declaration from assignment when you need the exit status. Write local out then out=$(cmd) so $? reflects the command, not the local builtin. Reserve the one-line local out=$(cmd) form for cases where the status does not matter.
  • Namespace nameref parameters to avoid collisions. Prefix internal nameref variables with an underscore or a function-specific tag so a caller's ordinary variable name is unlikely to match and trigger a circular reference.
  • Prefer namerefs over eval for indirection. Where older scripts used eval to build and assign variable names, a nameref does the same job more safely and readably, without the quoting hazards and injection risks of eval.
  • Document a function's output parameters. When a function fills caller variables through namerefs, state in a comment which positional arguments are output names and in what order, since the call site alone does not reveal that those strings are variable names.
  • Guard against unset nameref targets. When a nameref target may be unset or misspelled, check it explicitly rather than letting a silent empty read propagate. This turns a subtle wrong-value bug into a clear failure.
  • Choose iteration for deep or hot work. Namerefs make recursion cleaner but not free. When depth could be large or the function is called often, rewrite the recursion as a loop with an accumulator variable for speed and bounded stack use.

Practice Exercises

  1. Demonstrate dynamic scope. Write a helper that prints a variable it never sets, and two callers that each declare that variable local with different values before calling the helper. Show the helper printing each caller's value, and explain in a comment how this differs from lexical scope.
  1. A two-value nameref return. Write a function that, given the names of two caller variables and a pair of numbers, fills the first with their sum and the second with their product. Call it and print both results, and show that no subshell was involved by having the function also set a global side-effect that survives.
  1. Catch a masked exit status. Write a function that captures the output of a command that fails, first with local out=$(cmd) and then with a separate declaration and assignment. Print $? in each case and explain why only the second reports the real failure.
  1. Recursive accumulation through a nameref. Write a recursive function that counts down from N to 1, appending each number to a caller-supplied array or string through a nameref. Show the final accumulated result for N of 5, and explain why the accumulator must live in the caller rather than in a local.