Why loops repeat tasks efficiently in Bash Scripting - Performance Analysis
Loops help us repeat tasks many times without writing the same code again and again.
We want to see how the time it takes grows as we repeat more tasks.
Analyze the time complexity of the following code snippet.
for i in $(seq 1 n)
do
echo "Processing item $i"
done
This code prints a message for each item from 1 to n, repeating the task n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The echo command inside the loop.
- How many times: Exactly n times, once for each loop iteration.
As n grows, the number of times the task repeats grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 echo commands |
| 100 | 100 echo commands |
| 1000 | 1000 echo commands |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line as we add more items to process.
[X] Wrong: "The loop runs instantly no matter how big n is."
[OK] Correct: Each loop step takes some time, so more steps mean more total time.
Understanding how loops scale helps you explain how your scripts handle bigger tasks smoothly.
"What if we added a nested loop inside this loop? How would the time complexity change?"