Bash遍历多个数组

时间:2013-07-26 20:56:56

标签: arrays bash loops

我定义了多个数组:

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

我的数组语法出了什么问题?

2 个答案:

答案 0 :(得分:1)

您的脚本不正确。

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

    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
    

答案 1 :(得分: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的情况下,可能有某种方法可以做到这一点,但如果没有它,我就无法让间接工作。