shell script syntax: variable name to reference array

Go To StackoverFlow.com

1

This is close, but I'm having trouble referencing the second array in my loop. What should the syntax look like? $item is returning "1" instead of "a,b,c or d"

colors=( teal purple pink red green darkblue skyblue )
teal=( a b c d )


for color in ${colors[@]}
do
    echo $color

    for item in ${#{$color}[@]}
    do
        echo $item
    done

done
2012-04-03 23:01
by Dave Rau


5

You can do something like this:

mkt.sh

colors=( teal purple pink red green darkblue skyblue )
teal=( a b c d )
purple=( x y z )

for color in ${colors[@]}
do
    echo color: $color

    declare -a 'vals=("${'"$color"'[@]}")'
    for item in ${vals[@]}
    do
        echo "-- $item"
    done
done

Running:

$ ./mkt.sh 
color: teal
-- a
-- b
-- c
-- d
color: purple
-- x
-- y
-- z
color: pink
color: red
color: green
color: darkblue
color: skyblue
$ 

Credits:

2012-04-03 23:30
by icyrock.com
Thanks so much icyrock, I follow your code - Dave Rau 2012-04-04 00:09
Sure thing, glad to help - icyrock.com 2012-04-04 00:10