0

I want to print out the element in a list:

lst_1=(A B C)
for j in ${lst_1[@]};do echo $j ;done
A
B
C

this worked. But when I use variable on list name, it failed.

lst_1=(A B C)
lst_2=(D E F)

for i in 1 2;do \
    for j in ${lst_${i}[@]};do \
        echo $j ;done;done

-bash: ${lst_${i}[@]}: bad substitution
mike
  • 77
  • 6

1 Answers1

1

This will work:

lst_1=(A B C)
lst_2=(D E F)

for i in 1 2; do
    for j in $(eval echo \${lst_${i}[@]}); do
        echo $j ;
    done
done

This make the variable evaluations in 2 steps: first ${i} is substituted. Then the result (which will look like "echo ${lst_1[@]}" because the first dollar was escaped) will be interpreted by the eval command, resulting in the expanded array.

Note: not sure this solution will work in all cases (for example if the array elements will have spaces in them), other solutions might be better.

vladmihaisima
  • 2,119
  • 16
  • 20