if-then-else in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to run an if-then-else statement changes as the input changes.
Specifically, does adding more data make it slower?
Analyze the time complexity of the following code snippet.
#!/bin/bash
value=$1
if [ "$value" -gt 10 ]; then
echo "Value is greater than 10"
else
echo "Value is 10 or less"
fi
This script checks if a number is greater than 10 and prints a message accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single if-then-else condition check
- How many times: Exactly once per script run
The script runs the if-then-else check once no matter what the input number is.
| 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 time to run the if-then-else does not grow with input size; it stays constant.
[X] Wrong: "If the input number is bigger, the script takes longer because it has to compare more digits."
[OK] Correct: The if-then-else only checks the value once, no matter how big the number is. It does not look at each digit separately.
Understanding that simple condition checks run in constant time helps you explain how your scripts behave as inputs change. This clear thinking is useful in many scripting and automation tasks.
"What if we added a loop inside the if-then-else that runs n times? How would the time complexity change?"