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

标签 bash macos shell bsd

我有一堆这样的数组:

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/

相关文章:

linux - 如何在 bash 中使用 xargs 命令检查版本?

linux - 如何使用 bash 读取多个 CSV 文件并将它们正确附加到另一个文件?

android - 当我的 nexus 6p 处于恢复模式时,ADB 无法列出我的设备

python - 是否可以从 Python 获取 "high water mark"的内存使用情况?

shell - 是否可以在我的 shell 文件中使用 GitHub secret ?

database - postgres脚本遇到语法错误: unexpected end of file

Java 7 JRE 安装但未在 OSX Mountain Lion 上启用

Bash:如何使用局部变量同时捕获错误和回显值?

linux - while 循环中的 Case 语句,shell 脚本

linux - 我有一些代码有一个在终端上运行良好但从脚本运行时失败的命令