Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading