up vote 1 down vote favorite
Share on Facebook

here is my bash case

first case, this 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

link|flag

I think what I meant by "aliasing" is should be "indirection" in bash – uray Sep 2 at 22:17

2 Answers

up vote 1 down vote accepted

sorry, I solved it myself, last example should be like this :

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

In your answer, varAlias isn't an array, so you can do for varItem in $varAlias which is just doing word splitting. Because of that if any of your original array elements include spaces, they will be treated as separate words.

You can do scalar indirection like this: a=42; b=a; echo ${!b}.

You can do indirection to an array of scalars like this:

$ j=42; k=55; m=99
$ a=(j k m)
$ echo ${!a[1]}
55

Unfortunately, there's no satisfactory way to do the type of array indirection you're trying to do. You should be able to rework your code so that no indirection is needed.

See also BashFAQ/006.

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.