Default values for input in Bash Scripting - Time & Space Complexity
When a script uses default values for input, it often checks if input is given or not.
We want to see how this check affects the script's running time as input size changes.
Analyze the time complexity of the following code snippet.
#!/bin/bash
input=${1:-default}
for i in $(seq 1 5); do
echo "Processing $input - step $i"
done
This script sets a default value if no input is given, then runs a loop 5 times printing a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs 5 times.
- How many times: Exactly 5 times, fixed regardless of input.
The script runs the same 5-step loop no matter what input is given or if default is used.
| Input Size (n) | Approx. Operations |
|---|---|
| Empty or small input | 5 |
| Long input string | 5 |
| Very large input string | 5 |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the script runs in constant time, unaffected by input size.
[X] Wrong: "Using default values makes the script slower as input grows."
[OK] Correct: The default value check is a simple assignment and does not loop over input, so it does not slow down with bigger input.
Understanding how default inputs affect script speed helps you write reliable scripts that behave predictably no matter what input they get.
"What if the loop count depended on the length of the input string? How would the time complexity change?"