0

So, I have two arrays:

arr1=("A" "C" "E")
arr2=("B" "D" "F")

I have nested loops like this:

 for i in $(seq 1 $numberOfYears); 
    do
        echo "$i"
        for j in "${arr1[@]}";
            do
                echo ${arr1[j]} <---Keeps printing "A" 
                echo ${arr2[j]} <---Keeps printing "B" 
            done
    done

New to programmatic shell scripting. What would cause the inner for loop to correctly iterate through array1 when you reference the element like this: $j but not like this ${arr1[j]} and ${arr2[j]} ..? In all of my reading/searching, this should correctly iterate through both arrays.

My expected results:

Expected

 1ABCDEF
 2ABCDEF
 3ABCDEF

Actual

 1ABABAB
 2ABABAB
 3ABABAB

If I change ${arr1[j]} to $j it works fine, but I need to get the elements of arr2 as well, so I have to get it like ${arr2[j]}.

2
  • 1
    You are probably looking for for j in "${!arr1[@]}".... Commented Oct 31, 2018 at 14:34
  • 1
    Maybe associative array would work better? declare -A arr=([A]=B [C]=D [E]=F); for k in "${!arr[@]}"; do echo $k ${arr[$k]} ; done. Commented Oct 31, 2018 at 14:45

1 Answer 1

2

You're looping over the values of the array.

You can loop over the keys if you want, using "${!arr1[@]}" (add the !):

for i in $(seq 1 $numberOfYears); 
do
    echo "$i"
    for j in "${!arr1[@]}";
    do
        echo ${arr1[j]}
        echo ${arr2[j]}
    done
done

Otherwise, you are expanding parameters like ${arr1["A"]}, and since these keys are not defined, you get the first element of the array.

As an aside, you can also use a different style of loop to iterate over numeric keys:

for (( i = 0; i <= numberOfYears; ++i ))
do
  echo "$i"
  for (( j = 0; j < ${#arr1[@]}; ++j ))
  do
    echo "${arr1[j]}"
    echo "${arr2[j]}"
  done
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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