if-then-fi structure in Bash Scripting - Time & Space Complexity
We want to understand how the time a bash script takes changes when it uses an if-then-fi structure.
Specifically, we ask: How does the script's running time grow as input changes when using if-then-fi?
Analyze the time complexity of the following code snippet.
if [ "$1" -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is 10 or less"
fi
This script checks if the first input number is greater than 10 and prints a message accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single if condition check
- How many times: Exactly once per script run
The script checks the condition once, no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same regardless of input size.
Time Complexity: O(1)
This means the script runs in constant time, doing the same amount of work no matter the input.
[X] Wrong: "The if-then-fi structure takes longer if the input number is bigger."
[OK] Correct: The condition is checked once, so input size or value does not affect how many steps the script takes.
Understanding that simple condition checks run in constant time helps you explain script efficiency clearly and confidently.
"What if we added a loop inside the if block that runs n times? How would the time complexity change?"