Skip to content
AgileLogics
3 min read

break and continue

Prerequisites: while loops and reading files

  • break stops a loop completely.
  • continue skips to the next pass.
for n in {1..10}; do
  if (( n % 2 == 0 )); then
    continue
  fi
  if (( n > 7 )); then
    break
  fi
  echo "$n"
done
1
3
5
7

Even numbers are skipped; at 9, the loop ends.

Skipping lines while reading a file

cat > settings.conf <<'EOF'
# Application settings
port=8080

# Logging
level=debug
EOF

while IFS= read -r line; do
  [[ -z $line || $line == \#* ]] && continue
  echo "setting: $line"
done < settings.conf
setting: port=8080
setting: level=debug

Skipping blank lines and comments is a common step when reading configuration files. (\# escapes the # so it isn't read as a comment.)

break 2 exits two nested loops at once.