Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
I think what I meant by "aliasing" is should be "indirection" in bash –  uray Sep 2 '10 at 22:17
add comment

3 Answers

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
share|improve this answer
add comment

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.

share|improve this answer
add comment
up vote 1 down vote accepted

I solved it; last example should be like this:

eval varAlias=\${"myvar"$varname[@]}
for varItem in ${varAlias[@]}
do
    echo $varItem
done
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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