Take the 2-minute tour ×

Suppose I have some bash arrays:

A1=(apple trees)
A2=(building blocks)
A3=(color television)

And index J=2, how to get the array contents of A2?

share|improve this question
This is very cool. I consider myself a bash expert and I was always under the assumption that bash cannot do array indirection such as ${!ind[@]} but I never thought to introduce a temp var to solve it. –  SiegeX Jan 3 '11 at 5:08
Interesting question/answer! –  ring0 Jan 3 '11 at 5:44
You should post your answer as an answer. You will be able to accept it when the time limit expires. Here is an example of the usual way that arrays are used with indirection: d=13; e=24; f=35; a=(d e f); echo ${!a[1]} which results in "24". –  Dennis Williamson Jan 3 '11 at 5:51
add comment

2 Answers

up vote 14 down vote accepted

I've already found a resolution, this can be done by:

$ Aref=A$J
$ echo ${!Aref}
$ Aref=A$J[1]
$ echo ${!Aref}
$ Aref=A$J[@]
$ echo "${!Aref}"
building blocks
share|improve this answer
How can you assign to, say, A$J? You need a name without expansion to assign to, but A$J=(...) doesn't work. –  musiphil Feb 28 '13 at 6:54
add comment

It’s worth to note, that even an index will be substituted at time the variable is evaluated:

$ A2=(building blocks)
$ Aref=A2[index]
$ index=1
$ echo "${!Aref}"
share|improve this answer
FANTASTIC. years of shell scripting + reading the manual at least a dozen times + explicit attempts at exactly this failed to surface this little gem! note, like literal indexes, any arithmetic expression is valid, including nested expansions, eg. cycle=(0 1 2); ref='cycle[i++%${#cycle[*]}]'; echo ${!ref} ${!ref} ${!ref} ${!ref} ${!ref} ${!ref} # => 0 1 2 0 1 2 –  anthonyrisinger May 13 '13 at 3:35
I wonder if this is a feature explicitly intended to be so, or if we are exploiting side-effect of the indirect expansion, which could silently disappear from future releases. –  davide Jan 29 at 2:36
add comment

Your Answer


