buzzinolops
buzzinolops

Reputation: 321

How to evaluate a variable inside a variable bash scripting?

I have a bunch of arrays like this:

array1=("A" "B")
array2=("C" "D")
array3=("E" "F" "G")

And I want to loop over the arrays, and the elements in each. Here is how I'm trying to accomplish this:

for i in `seq 1 2`
do 
    for elm in ${array${i}[@]}
    do
        echo "the element in array$i is $elm" 
    done
done

But, this gives me:

./new_test.sh: line 6: ${array${i}[@]}: bad substitution

I sort of know that what I'm doing is wrong, because I don't want the first $ to evaluate the ${i} inside of it.

How do I prevent this?

Upvotes: 2

Views: 164

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

#!/bin/bash

array1=("A" "B")
array2=("C" "D")
array3=("E" "F" "G")

for i in "array"{1..3}"[@]"; do
    echo "$i"
    for el in "${!i}"; do
        echo "$el"
    done
done

Output is:

array1[@]
A
B
array2[@]
C
D
array3[@]
E
F
G

Upvotes: 0

Jahid
Jahid

Reputation: 22428

This should work:

var=array$i[@]
for elm in ${!var}
...

Example:

#!/bin/bash
array1=("A" "B")
array2=("C" "D")
array3=("E" "F" "G")

for i in `seq 1 2`
do 
    var=array$i[@]
    for elm in "${!var}"
    do
        echo "the element in array$i is $elm" 
    done
done

Output:

the element in array1 is A
the element in array1 is B
the element in array2 is C
the element in array2 is D


Indirect expansion (from bash manual):

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

Upvotes: 6

Related Questions