Accessing variables ($var and ${var}) in Bash Scripting - Time & Space Complexity
When we use variables in bash scripts, we often access their values using $var or ${var} syntax.
We want to understand how the time it takes to access these variables changes as the script grows or uses more variables.
Analyze the time complexity of the following code snippet.
#!/bin/bash
var="Hello"
echo $var
var2="World"
echo ${var2}
for i in 1 2 3 4 5; do
echo $var
echo ${var2}
done
This script sets two variables and prints them once, then prints them inside a loop five times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing variables using $var and ${var2} inside the loop.
- How many times: The variable access happens 2 times per loop iteration, repeated 5 times.
Each loop iteration accesses variables twice. As the number of iterations grows, the total variable accesses grow proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 variable accesses |
| 100 | 200 variable accesses |
| 1000 | 2000 variable accesses |
Pattern observation: The number of variable accesses grows linearly with the number of loop iterations.
Time Complexity: O(n)
This means the time to access variables grows directly in proportion to how many times you access them in a loop.
[X] Wrong: "Accessing a variable like $var is instant and does not add to execution time as the script grows."
[OK] Correct: While each access is fast, if you access variables many times in loops, the total time adds up and grows with the number of accesses.
Understanding how variable access scales helps you write efficient scripts and shows you can think about performance even in simple tasks.
What if we replaced the loop with nested loops accessing variables multiple times? How would the time complexity change?