Unsetting variables (unset) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to unset variables changes as we unset more variables in a script.
How does the cost grow when we remove variables one by one?
Analyze the time complexity of the following code snippet.
# Define some variables
var1="hello"
var2="world"
var3="!"
# Unset variables one by one
unset var1
unset var2
unset var3
This script sets three variables and then unsets each one individually.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each
unsetcommand removes one variable. - How many times: The
unsetcommand runs once per variable to remove.
Each variable unset takes a small, fixed amount of time. As you unset more variables, the total time grows directly with the number of variables.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 unset commands |
| 100 | 100 unset commands |
| 1000 | 1000 unset commands |
Pattern observation: The total time grows in a straight line as the number of variables increases.
Time Complexity: O(n)
This means the time to unset variables grows directly with how many variables you remove.
[X] Wrong: "Unsetting variables is instant no matter how many there are."
[OK] Correct: Each unset command takes some time, so more variables mean more total time.
Knowing how simple commands like unset scale helps you write efficient scripts and shows you understand how scripts behave as they grow.
"What if we unset all variables inside a loop instead of one by one? How would the time complexity change?"