Bash eval array variable name

arraybashlinuxscripting

Here is my bash case:

First case, this is what I want to do "aliasing" var with myvarA:

myvarA="variableA"
varname="A"
eval varAlias=\$"myvar"$varname
echo $varAlias

Second case for array variable and looping its members, which is trivial:

myvarA=( "variableA1" "variableA2" )
for varItem in ${myvarA[@]}
do
    echo $varItem
done

Now somehow I need to use "aliasing" technique like example 1, but this time for array variable:

eval varAlias=\$"myvar"$varname
for varItem in ${varAlias[@]}
do
    echo $varItem
done

But for last case, only first member of myvarA is printed, which is eval evaluate to value of the variable, how should I do var array variable so eval is evaluate to the name of array variable not the value of the variable.

Best Answer

The simplest form for parameter expansion is: ${parameter}.
Using braces in confused case is better way.

Considering of possibilities of being included spaces in array of "myvarA", I think this would be the answer.

#!/bin/bash -x
myvarA=( "variable  A1" "variable  A2" )
varname="A"

eval varAlias=( '"${myvar'${varname}'[@]}"' )
eval varAlias=( \"\${myvar${varname}[@]}\" ) # both works
for varItem in "${varAlias[@]}" # double quote and `@' is needed
do
    echo "$varItem"
done
Related Question