bash
4.3 added support for ksh93
-like namerefs.
So in bash-4.3 or above you can do:
a0[5]=whatever
x=0
typeset -n var="a$x"
printf '%s\n' "${var[5]}"
But note that's a reference (a pointer, not a copy) to the variable name, not the variable (the difference matters when you have several variables by the same name in different contexts like for local variables in functions).
bash
copied ksh
arrays with their awkward design. Making a copy of an array in bash
is difficult, you can use a helper function like:
copy_array() { # Args: <src_array_name> <dst_array_name>
eval '
local i
'"$2"'=()
for i in "${!'"$1"'[@]}"; do
'"$2"'[$i]=${'"$1"'[$i]}
done'
}
To be used for instance as:
$ a0[5]=123
$ x=0
$ copy_array "a$x" var
$ typeset -p var
declare -a var=([5]="123")
ksh
(and bash
which copied ksh
) is the only shell where arrays are sparse (or are associative arrays whose keys are limited to positive integers) (also the only arrays with indices starting at 0 instead of 1, or where $array
unintuitively doesn't expand to the elements but the element of indice 0). It's a lot easier with other shells.
rc
: array_copy = $array
fish
: set array_copy = $array
csh
: set array_copy = ($array:q)
zsh
or yash
: array_copy=("${array[@]}"}
For indirect copy (where $var
contains the source array name):
rc
: eval array_copy = '$'$var
fish
: eval set array_copy \$$var
csh
: eval "set array_copy = (\$${var}:q)"
zsh
: array_copy=("${(@P)var}")
yash
(or zsh
): eval 'array_copy=("${'"$var"'[@]}")'
tmp="arr$x[@]"
, the rest will work as is.