Bash Shell 多个数组上的嵌套 for 循环不会遍历所有元素

Bash Shell nested for loop on multiple arrays doesn't go though all elements

OUTER_LIST=(1 2)
INNER_LIST=(a b)
for (( i=0; i < ${#OUTER_LIST[@]}; i++ )); do
    echo "outer...${OUTER_LIST[$i]}"

    for (( i=0; i < ${#INNER_LIST[@]}; i++ )); do
        echo "inner...${INNER_LIST[$i]}"
    done
done

输出:

outer...1
inner...a
inner...b

问题:为什么只循环 OUTER_LIST 1 次?

您在内部循环中使用相同的循环变量 i,因此当第一次这样做时,i 将是 2,这超出了外循环。

使用不同的变量修复它:

#!/bin/bash

OUTER_LIST=(1 2)
INNER_LIST=(a b)
for (( i=0; i < ${#OUTER_LIST[@]}; i++ )); do
    echo "outer...${OUTER_LIST[$i]}"

    for (( j=0; j < ${#INNER_LIST[@]}; j++ )); do
        echo "inner...${INNER_LIST[$j]}"
    done
done

或者:

for outer in "${OUTER_LIST[@]}"; do
    echo "outer...$outer"

    for inner in "${INNER_LIST[@]}"; do
        echo "inner...$inner"
    done
done

输出:

outer...1
inner...a
inner...b
outer...2
inner...a
inner...b