How does `continue` affect nested loops?

QuestionsQuestions8 SkillsProDec, 16 2025
0164

That's an excellent follow-up question, as continue behaves slightly differently in nested loops compared to break!

In nested loops, the continue statement only affects the innermost loop it is part of. It causes the execution to jump to the next iteration of that innermost loop, leaving any outer loops unaffected.

Let's illustrate with an example:

#!/bin/bash

echo "Demonstration of continue in nested loops:"

for i in {1..3}; do # Outer loop
  echo "Outer loop iteration: $i"
  for j in {1..3}; do # Inner loop
    if [ $((i*j)) -eq 2 ]; then # If product of i and j is 2 (e.g., i=1, j=2 OR i=2, j=1)
      echo "  Skipping inner loop for i=$i, j=$j (product is 2)"
      continue # This 'continue' applies ONLY to the inner 'for j' loop
    fi
    echo "  Inner loop: i=$i, j=$j, Product=$((i*j))"
  done
done
echo "Loops finished."

Expected Output Breakdown:

  • i=1:
    • Outer: Outer loop iteration: 1
    • j=1: Inner loop: i=1, j=1, Product=1
    • j=2: i*j is 2. continue. (echo for inner loop is skipped for j=2).
      • Execution moves to j=3 of the inner loop.
    • j=3: Inner loop: i=1, j=3, Product=3
  • i=2:
    • Outer: Outer loop iteration: 2
    • j=1: i*j is 2. continue. (echo for inner loop is skipped for j=1).
      • Execution moves to j=2 of the inner loop.
    • j=2: Inner loop: i=2, j=2, Product=4
    • j=3: Inner loop: i=2, j=3, Product=6
  • i=3:
    • Outer: Outer loop iteration: 3
    • j=1: Inner loop: i=3, j=1, Product=3
    • j=2: Inner loop: i=3, j=2, Product=6
    • j=3: Inner loop: i=3, j=3, Product=9

You'd notice that when the condition i*j is 2 (which happens for (i=1, j=2) and (i=2, j=1)), the echo statement for the inner loop is skipped, but the outer loop continues normally, and the inner loop proceeds to its next iteration.

This is different from break, which would exit the entire inner loop and continue with the next iteration of the outer loop.

To affect an outer loop with continue, you'd need more elaborate logic, possibly involving flags or restructuring your loops. However, for most common use cases, continue impacting only the immediate loop it's in is exactly the desired behavior.

Does seeing how continue works in this nested example help clarify its scope?

0 Comments

no data
Be the first to share your comment!