我有一堆这样的数组:
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.
关于bash - 如何评估变量 bash 脚本中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37247273/