Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash indirect array addressing?

Tags:

arrays

bash

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?

like image 741
Xiè Jìléi Avatar asked Jan 03 '11 04:01

Xiè Jìléi


3 Answers

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

$ Aref=A$J
$ echo ${!Aref}
building
$ Aref=A$J[1]
$ echo ${!Aref}
blocks
$ Aref=A$J[@]
$ echo "${!Aref}"
building blocks
like image 161
Xiè Jìléi Avatar answered Nov 15 '22 08:11

Xiè Jìléi


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}"
blocks
like image 31
Reuti Avatar answered Nov 15 '22 09:11

Reuti


Today (with bash 4.3 and later), the best practice is to use nameref support:

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

declare -n A="A$J"
printf '%q\n' "${A[@]}"

...will properly emit:

building
blocks

This is also available as nameref A="A$J" on ksh93. See BashFAQ #6 for details.

like image 5
Charles Duffy Avatar answered Nov 15 '22 09:11

Charles Duffy