← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 5 of 7

Nameref Variables (declare -n) for Passing Arrays by Reference

A nameref is a variable that acts like a nickname for another variable, letting a function reach out and modify an array that belongs to the caller.

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

bash
#!/bin/bash
original="hello"
declare -n alias_var=original
echo "through alias: $alias_var"
alias_var="changed"
echo "original is now: $original"

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

bash
#!/bin/bash
add_item() {
    local -n target_array=$1
    target_array+=("$2")
}

fruits=("apple" "banana")
add_item fruits "cherry"
echo "fruits now: ${fruits[*]}"

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

bash
#!/bin/bash
square_into() {
    local -n result_ref=$1
    result_ref=$(( $2 * $2 ))
}

square_into answer 7
echo "7 squared is $answer"
Common Mistakes
  1. 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.
  2. Naming the nameref parameter the same as the variable being referenced in the caller, which can create a self-reference error.
  3. Not realizing declare -n is a bash 4.3+ feature, so it won't work in scripts intended for very old bash or POSIX sh.
Chapter Summary
  • declare -n ref=varname makes ref an alias for whatever variable varname names, including arrays.
  • Passing an array's NAME (not "${arr[@]}") as an argument, then binding it with declare -n inside 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.