Variable assignment (no spaces around =) in Bash Scripting - Time & Space Complexity
Let's see how the time it takes to run a simple variable assignment changes as we run it multiple times.
We want to know how the cost grows when we assign values repeatedly.
Analyze the time complexity of the following code snippet.
for i in {1..1000}
do
value=$i
echo $value
done
This code assigns a number to a variable and prints it, repeating 1000 times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Variable assignment and printing inside a loop.
- How many times: The loop runs exactly n times, where n is the number of iterations.
Each time we increase the number of loop runs, the total work grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments and prints |
| 100 | 100 assignments and prints |
| 1000 | 1000 assignments and prints |
Pattern observation: Doubling the input doubles the work done.
Time Complexity: O(n)
This means the time grows in a straight line with the number of assignments we do.
[X] Wrong: "Variable assignment is instant and does not add to time complexity."
[OK] Correct: Even simple assignments inside a loop add up as the loop runs more times, so total time grows with input size.
Understanding how simple repeated steps add up helps you explain script performance clearly and confidently.
"What if we replaced the loop with a function call inside the loop? How would the time complexity change?"