Infinite loops in Bash Scripting - Time & Space Complexity
Infinite loops run without stopping, so their execution time keeps growing endlessly.
We want to understand how this affects the time complexity of a script.
Analyze the time complexity of the following code snippet.
while true; do
echo "Running..."
sleep 1
done
This script prints a message every second forever, never stopping.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The infinite while loop that repeats printing and sleeping.
- How many times: It runs endlessly without stopping.
Since the loop never ends, the number of operations keeps increasing without limit.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 seconds | About 10 prints and sleeps |
| 100 seconds | About 100 prints and sleeps |
| 1000 seconds | About 1000 prints and sleeps |
Pattern observation: The operations grow linearly with time, but since it never stops, it grows without bound.
Time Complexity: O(\infty)
This means the script runs forever, so the time it takes keeps increasing endlessly.
[X] Wrong: "Infinite loops have a fixed time complexity like other loops."
[OK] Correct: Infinite loops never stop, so their execution time is not fixed or bounded like normal loops.
Understanding infinite loops helps you recognize when a script might run forever, which is important for writing reliable automation.
"What if we add a condition inside the loop to stop after 100 iterations? How would the time complexity change?"