break and continue in Bash Scripting - Time & Space Complexity
When using break and continue in bash loops, it is important to see how they affect the total steps the script runs.
We want to know how these commands change the time it takes as the input grows.
Analyze the time complexity of the following code snippet.
for i in {1..100}
do
if [ $i -eq 50 ]; then
break
fi
echo "Number $i"
done
This script prints numbers from 1 up to 49, then stops the loop early using break.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop iteration from 1 to 100.
- How many times: Loop runs until it hits 50, then stops early due to
break.
Because the loop stops early at 50, the number of steps does not grow with the full input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 (loop runs fully) |
| 100 | 50 (stops early at 50) |
| 1000 | 50 (still stops at 50) |
Pattern observation: The loop does not always run to the full input size because break stops it early.
Time Complexity: O(1)
This means the loop runs only up to a fixed number of steps (k), regardless of input size.
[X] Wrong: "The loop always runs n times, so time complexity is always O(n)."
[OK] Correct: Because break can stop the loop early, the actual steps can be fewer than n.
Understanding how break and continue affect loops shows you can reason about real script behavior, not just the code structure.
"What if we replaced break with continue? How would the time complexity change?"