Search code examples
bash

Can you assign associative arrays to variables in bash?


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?


Solution

  • 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