Search code examples
arraysbashnested-for-loop

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

Output:

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

Question: why does it loop OUTER_LIST only 1 time ?


Solution

  • You use the same loop variable, i, in the inner loop so when that is done the first time, i will be 2 which is out of the range of the outer loop.

    Fix it by using a different variable:

    #!/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
    

    Alternatively:

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

    Output:

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