0
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 ?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

yes, my bad :D. thanks.
@chuongvo You're welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.