Please use
[code][/code] tags around your code, to preserve formatting and to improve readability.
Your question really has little to do with arrays specifically. What you're asking for is called indirect referencing.
eval is one way to do it, but it's certainly not recommended usually. eval has security issues. In a nutshell, you should never use it on any string where you don't have complete control over the contents, and can't determine what the actual eval'd command would look like and do.
http://mywiki.wooledge.org/BashFAQ/048
Depending on what your final purpose is, there are a few other, probably better, options. To start with, bash has a dedicated indirect reference expression "
${!variable}". To re-use the above example:
Code:
$ name=array
$ array=( one two )
$ echo "${!name[0]}"
one
Note however that using
${!name[@]} or
${!name[*]} will output a list of the all the existing index numbers of that array instead.
Edit: D'oh! I just realized this doesn't quite work as expected. ${!name[0]} evaluates to "one", because it's the same as ${!name}. But ${!name[1]} does not evaluate to anything, as it's trying to reference a non-existent array entry. In short, it will work when expanding simple variables, but can't be used for dynamic array names.
You could however indirectly reference the index number instead, although now we're getting really nested!
Code:
$ foo=0
$ name=foo
$ array=( one two )
$ echo "${array[${!name}]}"
one
There are also now associative arrays, which are arrays that use character strings as indexes, rather than numbers. Most of the things that used to need indirect referencing can now be handled better with them.
Code:
$ declare -A array
$ array=( [one]=foo [two]=bar )
$ num=( one two )
$ echo "${array[${num[0]}]}"
foo
$ echo "${array[${num[1]}]}"
bar
More on indirect referencing here :
http://mywiki.wooledge.org/BashFAQ/006