for loop with range ({1..10}) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to run a bash for loop changes as we increase the number of items it goes through.
Specifically, how does the loop with a range like {1..10} behave when the range grows?
Analyze the time complexity of the following code snippet.
for i in {1..10}
do
echo "Number: $i"
done
This code runs a loop from 1 to 10 and prints each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs the echo command once for each number in the range.
- How many times: Exactly as many times as the numbers in the range (10 times here).
As the range grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 echo commands |
| 100 | 100 echo commands |
| 1000 | 1000 echo commands |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line with the number of items in the range.
[X] Wrong: "The loop runs in constant time no matter how big the range is."
[OK] Correct: Each number in the range causes the loop to run once, so more numbers mean more work.
Understanding how loops grow with input size is a key skill. It helps you explain how your scripts will behave with bigger data, which is important in real work.
"What if we changed the loop to run from 1 to 10 but printed only every second number? How would the time complexity change?"