如何评估变量 bash 脚本中的变量?

How to evaluate a variable inside a variable bash scripting?

我有一堆这样的数组:

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

我想遍历数组和每个数组中的元素。以下是我尝试实现此目的的方法:

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

但是,这给了我:

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

我知道我做的是错的,因为我不希望第一个 $ 评估里面的 ${i}

如何防止这种情况发生?

这应该有效:

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

示例:

#!/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

输出:

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.

#!/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

输出为:

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