7.3. Loop Control: break and continue#

Fine-tune loop behavior by exiting early or skipping iterations.

7.3.1. break N and continue N#

7.3.1.1. break N: Exit Multiple Levels#

# break 1 (or just break): exit current loop
# break 2: exit current AND parent loop
# break 3: exit 3 levels, etc.

for i in 1 2 3; do
  for j in a b c; do
    if [ "$j" = "b" ]; then
      break 2  # Exit both loops
    fi
    echo "$i-$j"
  done
done

echo "Done"

Output:

1-a
Done

7.3.1.2. continue N: Skip Multiple Levels#

for i in 1 2 3; do
  for j in a b c; do
    if [ "$j" = "b" ]; then
      continue 2  # Skip to next $i iteration
    fi
    echo "$i-$j"
  done
done

Output:

1-a
2-a
3-a
Done

Real example: matrix processing

#!/bin/bash

for row in {1..10}; do
  for col in {1..10}; do
    if [ $((row * col)) -gt 50 ]; then
      break 2  # Exit both loops when product > 50
    fi
    echo -n "$((row * col)) "
  done
  echo
done

7.3.2. break N and continue N#

Control nested loops:

7.3.2.1. Syntax#

for item in list; do
  if [ skip_condition ]; then
    continue  # Skip to next iteration
  fi
  # Normal processing
done

Real example: skip empty lines

#!/bin/bash

while IFS= read -r line; do
  [ -z "$line" ] && continue  # Skip empty lines
  
  echo "Processing: $line"
done < input.txt

Real example: skip certain files

#!/bin/bash

for file in *; do
  # Skip directories
  [ -d "$file" ] && continue
  
  # Skip backup files
  [[ "$file" == *.bak ]] && continue
  
  echo "Process: $file"
done

Real example: skip comments

#!/bin/bash

while IFS= read -r line; do
  # Skip comments
  [[ "$line" =~ ^# ]] && continue
  # Skip empty lines
  [ -z "$line" ] && continue
  
  echo "Line: $line"
done < config.txt

7.3.3. continue: Skip to Next Iteration#

Skip rest of loop body and jump to next iteration:

7.3.3.1. Syntax#

for item in list; do
  if [ condition ]; then
    break  # Exit the loop immediately
  fi
done

echo "Loop exited"

Real example: search for file

#!/bin/bash

for file in *.log; do
  if grep -q "ERROR" "$file"; then
    echo "Found error in $file"
    break  # Stop searching after first error
  fi
done

Real example: menu system

#!/bin/bash

while true; do
  echo "1. Start"
  echo "2. Stop"
  echo "3. Exit"
  read -p "Choose: " choice
  
  case $choice in
    1) echo "Starting..." ;;
    2) echo "Stopping..." ;;
    3) echo "Goodbye!"; break ;;  # Exit loop
    *) echo "Invalid" ;;
  esac
done

7.3.4. break: Exit Loop Early#

Stop looping immediately and jump to code after loop: