zhaooyue
zhaooyue

Reputation: 43

bash script dictionary get values by key?

one of my recent tasks includes creating a dictionary structure in Linux Shell. I have tried below code

    declare -A item_1
    item_1["value"]="hello"
    temp=item_1
    eval result="${item_1["value"]}" #Approach 1
    eval result="${$temp["value"]}" #Approach 2
    echo $result

by doing this Approach 1 can get value "hello", but how can I get Approach 2 print the same value by using $temp?

Upvotes: 1

Views: 10394

Answers (1)

Nikolay Nikolov
Nikolay Nikolov

Reputation: 13

You will need to introduce a new variable since bash/sh doesn't do nested expansions. Then make an indirect reference and voila:

temp_expr="$temp[value]"
result=${!temp_expr}

Upvotes: 1

Related Questions