Bash eval array variable name
Solution 1
I solved it; last example should be like this:
eval varAlias=\${"myvar"$varname[@]}
for varItem in ${varAlias[@]}
do
echo $varItem
done
Solution 2
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
Solution 3
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.
Solution 4
It looks like you're trying to indirectly reference an array from the index of another.
You might like to do something like:
arr_one[0]=arr_two[@]
From there you can do:
cmd "${!arr_one[0]}"
...to indirectly reference a full expansion of "${arr_two[@]}"
. As near as I can tell, there is no direct method of indexing further. For example "${!arr_one[0][1]}"
doesn't work as I'd hope (at least, not in bash
) but you can do "${!arr_one[0]1:1}"
and similar to slice the expansion as you could any other array. The end result is something like the 2-dimensional array structure that some other, more capable shells offer.
Related videos on Youtube
Comments
-
uray over 1 year
Here is my bash case:
First case, this is what I want to do "aliasing"
var
withmyvarA
: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 iseval
evaluate to value of the variable, how should I do var array variable soeval
is evaluate to the name of array variable not the value of the variable.-
Admin over 13 yearsI think what I meant by "aliasing" is should be "indirection" in bash
-