0

我定义了多个数组:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

我需要遍历所有数组的所有元素。以下是我使用的语法:

for j in {1..3}
do
    for (( k = 0 ; k < ${#array$j[*]} ; k++ ))
    do
        #perform actions on array elements, refer to array elements as "${array$j[$k]}"
    done
done

但是,上面的代码片段失败并显示消息

k < ${#array$j[*]} : bad substitution and 
${array$j[$k]}: bad substitution

我的数组语法有什么问题?

4

2 回答 2

1

你的脚本不正确。

  1. 首先,不应该用逗号分隔 3 个数组中的各种元素。
  2. 然后使用数组名作为变量,你需要使用间接

以下应该工作:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

for j in {1..3}
do
    n="array$j[@]"
    arr=("${!n}")
    for (( k = 0 ; k < ${#arr[@]} ; k++ ))
    do
        #perform actions on array elements, refer to array elements as "${array$j[$k]}"
        echo "Processing: ${arr[$k]}"
    done
done

这将处理所有 3 个数组并给出以下输出:

Processing: el1
Processing: el2
Processing: el3
Processing: el4
Processing: el5
Processing: el10
Processing: el12
Processing: el14
Processing: el5
Processing: el4
Processing: el11
Processing: el8
于 2013-07-26T21:29:30.603 回答
0

这个:

array1=(el1 el2 el3 el4 el5)
array2=(el10 el12 el14)
array3=(el5 el4 el11 el8)

for j in {1..3} ; do
    # copy array$j to a new array called tmp_array:
    tmp_array_name="array$j[@]"
    tmp_array=("${!tmp_array_name}")

    # iterate over the keys of tmp_array:
    for k in "${!tmp_array[@]}" ; do
        echo "\${array$j[$k]} is ${tmp_array[k]}"
    done
done

打印这个:

${array1[0]} is el1
${array1[1]} is el2
${array1[2]} is el3
${array1[3]} is el4
${array1[4]} is el5
${array2[0]} is el10
${array2[1]} is el12
${array2[2]} is el14
${array3[0]} is el5
${array3[1]} is el4
${array3[2]} is el11
${array3[3]} is el8

可能有一些方法可以在不创建的情况下做到这一点tmp_array,但没有它我无法让间接工作。

于 2013-07-26T21:29:44.580 回答