Tilde expansion (~) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to process tilde expansion changes as the input grows.
Specifically, how does bash handle the shortcut for home directories when many paths use ~?
Analyze the time complexity of the following bash snippet using tilde expansion.
for path in ~/docs ~/downloads ~/pictures; do
echo "$path"
done
This code loops over a few paths starting with ~ and prints each expanded path.
Look for repeated actions that affect time.
- Primary operation: Expanding ~ to the full home directory path.
- How many times: Once per path in the loop (3 times here).
Each time the script sees a path starting with ~, it replaces it with the home directory.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 expansions |
| 100 | 100 expansions |
| 1000 | 1000 expansions |
Pattern observation: The number of expansions grows directly with the number of paths using ~.
Time Complexity: O(n)
This means the time to expand all ~ grows linearly with how many paths need expanding.
[X] Wrong: "Tilde expansion happens once and then applies to all paths instantly."
[OK] Correct: Each path with ~ is expanded separately, so more paths mean more expansions.
Understanding how simple expansions scale helps you reason about script performance and efficiency in real tasks.
What if we changed the script to use absolute paths instead of ~? How would the time complexity change?