0
0
Bash Scriptingscripting~5 mins

break and continue in Bash Scripting

Choose your learning style9 modes available
Introduction
Use break and continue to control loops easily. They help you stop or skip parts of a loop without extra code.
Stop a loop early when a condition is met, like finding a match in a list.
Skip one round of a loop when some data is not valid.
Exit nested loops quickly when you have the result you want.
Avoid running unnecessary commands inside loops.
Control flow in scripts that process files or user input step-by-step.
Syntax
Bash Scripting
break [n]
continue [n]
break stops the loop immediately. If you give a number n, it breaks out of n nested loops.
continue skips the rest of the current loop round and moves to the next iteration. If you give n, it continues the nth enclosing loop.
Examples
Stops the loop when i equals 3, so it prints 1 and 2 only.
Bash Scripting
for i in {1..5}; do
  if [[ $i -eq 3 ]]; then
    break
  fi
  echo $i
done
Skips printing 3 but continues the loop for other numbers.
Bash Scripting
for i in {1..5}; do
  if [[ $i -eq 3 ]]; then
    continue
  fi
  echo $i
done
Breaks loop on 'yes', skips rest on 'no', asks again otherwise.
Bash Scripting
while true; do
  read -p "Enter yes or no: " answer
  if [[ $answer == "yes" ]]; then
    break
  elif [[ $answer == "no" ]]; then
    continue
  fi
  echo "Please answer yes or no."
done
Sample Program
This script loops from 1 to 5. It skips printing 2 and stops completely when it reaches 4.
Bash Scripting
#!/bin/bash

for i in {1..5}; do
  if [[ $i -eq 4 ]]; then
    echo "Reached 4, breaking the loop."
    break
  fi
  if [[ $i -eq 2 ]]; then
    echo "Skipping 2"
    continue
  fi
  echo "Number: $i"
done
OutputSuccess
Important Notes
Use break and continue carefully to keep your loops clear and easy to read.
In nested loops, break and continue can take a number to affect outer loops.
Always test your loops to make sure break and continue behave as expected.
Summary
break stops the loop immediately and exits it.
continue skips the current loop round and moves to the next one.
Both help control loops simply without extra conditions.