I have a few different associative arrays as variables:
declare -A FIRST=( [hello]=world [foo]=bar )
declare -A SECOND=( [bonjour]=monde [fu]=ba )
What I'd like to be able to do is take a third variable and assign it to one or the other, something like:
usethisarray=$FIRST
or maybe
declare -a usethisarray=$FIRST
But neither of those really work. Can I get a level of indirection to point at the associative array I need?
Note to readers: this answer is from 2013. You should now be using @ryenus's answer.
bash has variable indirection but it's kind of a pain to use:
$ declare -A FIRST=( [hello]=world [foo]=bar )
$ alias=FIRST
$ echo "${!alias[foo]}"
$ item=${alias}[foo]
$ echo ${!item}
bar
The answer is yes, and the reference variable needs to be a nameref (declare -n
) for it to be used with arrays:
declare -A FIRST=( [hello]=world [foo]=bar )
declare -A SECOND=( [bonjour]=monde [fu]=ba )
#### ordinary variable assignment does NOT work
declare any_var=FIRST
echo -e '${any_var[@]}:' "${any_var[@]}"
echo -e '${!any_var[@]}:' "${!any_var[@]}"
echo -e '${#any_var[@]}:' "${#any_var[@]}"
#### nameref works, via 'declare -n' or 'local -n'
declare -n arr_ref=SECOND
echo '${arr_ref[@]}:' "${arr_ref[@]}"
echo '${!arr_ref[@]}:' "${!arr_ref[@]}"
echo '${#arr_ref[@]}:' "${#arr_ref[@]}"
${any_var[@]}: FIRST
${!any_var[@]}: 0
${#any_var[@]}: 1
${arr_ref[@]}: monde ba # values of the associative array / map
${!arr_ref[@]}: bonjour fu # keys of the associative array / map
${#arr_ref[@]}: 2 # size of the associative array / map
See https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameters
Array variables cannot be given the nameref attribute. However, nameref variables can reference array variables and subscripted array variables.
Meanwhile, variable indirection, or more correctly indirect expansion, which also uses the exclamation point (!), it requires the variable or parameter to be NOT a nameref:
If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With