Namerefs and dynamic scoping
A nameref is a variable whose value names another variable; operations through the reference normally act on that target. declare -n and local -n are available in Bash 4.3 and later. This can implement a helper that updates a caller variable without emitting data through stdout. Names are resolved in Bash dynamic scope, so a helper with an internal local of the same name can accidentally redirect its own reference. Use trusted fixed names, document the target contract, avoid collisions and cycles, and do not accept arbitrary external variable names or subscript expressions. unset -n ref removes the reference itself; ordinary unset ref can remove its target. A nameref may refer to an array or array element, but the nameref attribute cannot be applied to an array variable itself. declare -p helps inspect attributes. The localvar_inherit shopt option changes how a newly declared local receives a value and attributes from an outer binding (except nameref). localvar_unset affects visibility of a local unset from an inner function. Prefer explicit initialization and predictable interfaces rather than depending on global options.
Conceptual lookup: bm_ref → name result → nearest visible binding. The binding is selected through dynamic scope, not fixed to the global variable. Use declare -p to inspect the reference attribute itself. The -v test alone cannot distinguish an absent reference from a reference to an unset target.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Write through a trusted name
result=beforeupdate() { local -n bm_ref=result || return 1 bm_ref=after}update || exit 1printf '%s\n' "$result"Expected stdout:
afterThe reference resolves to the caller-visible result variable.
Observe dynamic name collision
result=outerupdate() { local result=inner local -n bm_ref=result bm_ref=changed printf 'inside=%s\n' "$result"}updateprintf 'outside=%s\n' "$result"Expected stdout:
inside=changedoutside=outerThe local result shadows the outer binding, so the outer value does not change.
Remove reference without removing target
target=keepdeclare -n ref=target || exit 1unset -n ref || exit 1printf 'target=%s\n' "$target"if declare -p ref >/dev/null 2>&1; then exit 1; fiprintf 'reference=gone\n'Expected stdout:
target=keepreference=goneThe -n flag removes the reference itself rather than the target.
Common mistakes
Never use arbitrary user-supplied names as nameref targets. A local variable named like the target can shadow it.
Practice
Build a helper with a trusted fixed output name and test two calls. Then demonstrate a local-name collision in a separate script and remove it using distinct names.
Next: Shell option interactions