Nameref Variables (declare -n) for Passing Arrays by Reference
In this page:
Creating a Basic Nameref
declare -n ref=varname makes ref behave as an alias for varname: reading or writing ref actually reads or writes the variable named by varname, indirectly.
Example: Creating a Basic Nameref
#!/bin/bash
original="hello"
declare -n alias_var=original
echo "through alias: $alias_var"
alias_var="changed"
echo "original is now: $original"
Login to try C/C++/Java/PHP code in the editor
Modifying a Caller's Array by Reference
Passing an array's name as a plain string argument, then binding it inside the function with declare -n, lets the function append to or modify the caller's actual array directly, instead of only operating on a disconnected copy.
Example: Modifying a Caller's Array by Reference
#!/bin/bash
add_item() {
local -n target_array=$1
target_array+=("$2")
}
fruits=("apple" "banana")
add_item fruits "cherry"
echo "fruits now: ${fruits[*]}"
Login to try C/C++/Java/PHP code in the editor
Returning Multiple Values via a Nameref
Namerefs also work for scalar variables, giving functions a clean way to "return" a computed value into a caller-provided variable name instead of relying on global state or command substitution.
Warning: Avoid naming the nameref parameter the same as the variable name passed in, e.g. calling square_into result_ref 7 would create a self-referencing error.
Example: Returning Multiple Values via a Nameref
#!/bin/bash
square_into() {
local -n result_ref=$1
result_ref=$(( $2 * $2 ))
}
square_into answer 7
echo "7 squared is $answer"
Login to try C/C++/Java/PHP code in the editor
- Forgetting that bash functions normally receive array arguments by expanding them into separate words, losing the array structure; passing the array's NAME and using a nameref preserves it.
- Naming the nameref parameter the same as the variable being referenced in the caller, which can create a self-reference error.
- Not realizing
declare -nis a bash 4.3+ feature, so it won't work in scripts intended for very old bash or POSIX sh.
declare -n ref=varnamemakesrefan alias for whatever variablevarnamenames, including arrays.- Passing an array's NAME (not
"${arr[@]}") as an argument, then binding it withdeclare -ninside the function, lets the function read and modify the caller's actual array. - Namerefs avoid the common workaround of using global variables to get array data out of a function.
- Give the nameref parameter a distinct name from any variable it might reference to avoid the "circular reference" error.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first:
- getopts for Parsing Command-Line Flags
- Positional Parameters and shift
- Process Substitution in Practice (diff <(...) <(...))
- Arrays of Arguments ("$@" vs "$*" Quoting Difference)
- Nameref Variables (declare -n) for Passing Arrays by Reference
- Heredoc Templating (Generating a Config File from Variables)
- Default/Fallback Argument Handling