bashdictionaryvariablesindirect-variable

why indirect variable reference not work in bash dictionary


I know it( ! indirect variable reference ${!parameter}) will work in the general variable, but I need to use it in dictionary, and it doesn't work. Could somebody know the reason and how to achieve it?

I only konw the dictionary name and the key name, how to get the value in the dictionary?

#!/bin/bash
declare -A a_dict
a_dict=(
    ['aa']='valueA'
    ['ab']='valueB'
)

declare -A b_dict
b_dict=(
    ['ba']='valueA'
    ['bb']='valueB'
)

indirect_var(){
    name=$1
    key=$2
    echo ${!name[$key]}
}

indirect_var a_dict aa

Solution

  • In comments pmf has already provided a working function using an indirect reference.

    If running bash 4.3+ another option would be a nameref, eg:

    get_val() {
        local -n _var="$1"          # -n == nameref
        echo "${_var[$2]}"
    }
    
    ### or as a one-liner:
    
    get_val() { local -n _var="$1"; echo "${_var[$2]}"; }
    

    Taking for a test drive:

    $ get_val a_dict aa
    valueA
    
    $ get_val b_dict bb
    valueB
    
    $ get_val b_dict xyz
                              # blank output
    
    $ get_val c_dict xyz
                              # blank output