Example: Pass two separate arrays to a function.
#!/bin/bash
foo () {
declare -n array1="$1"
declare -n array2="$2"
echo 'The 1st array:'
printf '\t%s\n' "${array1[@]}"
echo 'The 2nd array:'
printf '\t%s\n' "${array2[@]}"
}
a=( 1 2 3 )
b=( a b c )
foo a b
Testing:
$ bash script.sh
The 1st array:
1
2
3
The 2nd array:
a
b
c
Doing the same thing without the use of name reference variables would have been difficult and would probably involve either changing the function to only ever handle one array each call, or having it take the number of elements in each of the two arrays as extra arguments, or using eval
in some way (which is difficult to do correctly).
With the use of name reference variables in the function, no esoteric syntax is needed to use the data in the arrays passed (as names) to the function, and the function is able to use the name reference variables as ordinary arrays.
In the function, the two variables array1
and array2
references, i.e. can be used as, the variables passed by name in $1
and $2
. They are name references.
This is similar to a "call by reference" in e.g. C++ I believe, but instead of using &variable
on the calling side (as in C++), the receiving side declares a local variable as a reference.