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?
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
A$J? You need a name without expansion to assign to, but A$J=(...) doesn't work.printf -v "A$J" '%s' "value to assign" will do the trick. See BashFAQ #6.printf -v works only for a single value, not for arrays, and read -a can split a string into arrays but is subject to the delimiter and the word separator, and cannot write to an associative array. declare seems to be the most versatile: declare "A$J=hello", declare -a "A$J=(hello world)", declare -A "A$J=([x]=hello [y]=world)".read appears to still do the trick: read -r 'arr[1]' <<<'hello'; declare -p arr behaves as-intended.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
cycle=(0 1 2); ref='cycle[i++%${#cycle[*]}]'; echo ${!ref} ${!ref} ${!ref} ${!ref} ${!ref} ${!ref} # => 0 1 2 0 1 2Today (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.
${!ind[@]}but I never thought to introduce a temp var to solve it.d=13; e=24; f=35; a=(d e f); echo ${!a[1]}which results in "24".