1

Here is an expected behavior for associated array in bash

$ declare -A PC=( [Monitor]=Dell [CPU]=HP )
$ echo ${PC[CPU]}
HP

This gives me HP as output

Lets say I have these PC,Monitor amd CPU values stored in variable a , b and c. I am trying fetch the details now but I am getting "bad substitution" error when trying so.

$ a=PC; b=Dell; c=HP
$ echo ${$a[$b]}
bash: ${$a[$b]}: bad substitution


$ echo ${PC[$b]}
Dell

${PC[$b]} however is returning expected output but not {$a[$b]}

Not sure how this can be achieved. Thanks in advance.

1
  • Syntax aside, neither Dell nor HP is a key in the associative array; they are values associated with the keys Monitor and CPU, respectively. Commented Jan 5, 2021 at 19:29

1 Answer 1

1

What you are trying to do is called indirection - using one variable as the name of another variable.

In bash you do this for normal variables using the syntax ${!var}, as in

a=5
b=a
echo ${!b} # 5

Unfortunately this won't work how you want for an array variable because the syntax ${!array[*]} means something else (getting all keys from an associative array).

Instead, as suggested by a comment below, you can create a string for the entire reference and then use redirection on that:

lookup="$a[$b]"
echo ${!lookup} # will give Dell in your example
Sign up to request clarification or add additional context in comments.

1 Comment

Indirection does work for arrays; you just need to construct an appropriate value consisting of the array name and the index. For example, t="PC[Monitor]"; echo "${!t}" will output Dell. Assuming a=PC and b=Monitor, t="$a[$b]" works as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.