1

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?

zhaooyue
  • 43
  • 1
  • 6
  • You are looking for indirect variables. See e.g. http://stackoverflow.com/questions/8515411/bash-indirect-expansion-please-explain – tripleee Sep 21 '16 at 15:11
  • If you hit a point where you need this kind of programming then: either Bash is the wrong language for the job, or your design needs rethinking. This is especially true if you're not an experienced scripter. Also note that in _Approach 1_, `eval` is useless; more generally, such uses of `eval` are very dangerous as they can lead to arbitrary code execution. – gniourf_gniourf Sep 21 '16 at 15:14
  • If you find yourself needing to indirectly reference a parameter via a string containing the parameter's name, that's is a sign that you have a design problem. It might be a language mismatch (e.g. bash doesn't have nested structures or a way to pass whole associative arrays to functions), but it could also be a poor design decision. Either way, I would spend some time rethinking. – Mark Reed Sep 21 '16 at 16:29

1 Answers1

1

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}