Skip to content

Files

Latest commit

 

History

History
39 lines (28 loc) · 954 Bytes

SC2165.md

File metadata and controls

39 lines (28 loc) · 954 Bytes

Pattern: Nested loop overrides the index variable of its parent

Issue: -

Description

When nesting loops, especially arithmetic for loops, using the same loop variable can cause unexpected results.

Example of incorrect code:

for((i=0; i<10; i++))
do
  for i in *
  do
    echo "$i"
  done
done

Here i will contain the last filename from the inner loop, which will be interpreted as a value in the next iteration out the outer loop. This results in either an infinite loop or a syntax error, depending on whether the last filename is a valid shell variable name.

In nested for-in loops, variable merely shadow each other and won't cause infinite loops or syntax errors, but reusing the variable name is rarely intentional.

Example of correct code:

for((i=0; i<10; i++))
do
  for j in *
  do
    echo "$j"
  done
done

Further Reading