带有未知数组的 ba​​sh for 循环

带有未知数组的 ba​​sh for 循环

我需要对数组 edg_cdi 中的元素执行 for 循环,但我知道它是那个数组,因为我的输入参数是 chosen='cdi'。如果是 chosen='cdt'(或许多其他),则选定的数组将有所不同。

chosen='cdi'

edg_cdi=('40' '46' '37' '43')
edg_cdt=('69' '24' '177' '25')

string='edg_'
wholename=$string$chosen

for i in "${ WHAT_TO_WRITE_HERE [@]}"
do
  echo $i
done

期望的输出是四个回声:

40
46
37
43

答案1

您可以将变量间接引用与适当的数组一起使用(与 @user1330614 的答案不同,后者使用普通变量伪造数组)。棘手的是,您必须在[@]间接引用的变量中包含数组元素(或所有元素)。如下所示:

edg_cdi=('40' '46' '37' '43')
wholename="edg_cdi"             # Same value original code generates
wholearray="${wholename}[@]"    # This includes the array name AND "[@]"
for i in "${!wholearray}"; do
    #...etc

例如,为了获取数组的第 n 个元素,可以使用以下命令:

n=3    # The element number we want
wholename_n="${wholename}[n]"    # Note that n does not have a $; it won't be resolved until use
dosomethingwith "${!wholename_n}"    # this resolves n and gets the 3rd element
n=2
dosomethingwith "${!wholename_n}"    # this re-resolves n and gets the 2nd element

答案2

你的代码应该是这样的

chosen='cdi'

edg_cdi="40 46 37 43"
edg_cdt="69 24 177 25"

string='edg_'
wholename=$string$chosen

for i in ${!wholename}
do
  echo $i
done

正如解释的那样这里

相关内容