if-elif-else in Bash Scripting - Time & Space Complexity
Let's see how the time it takes to run an if-elif-else decision changes as input changes.
We want to know how many steps the script takes when checking conditions.
Analyze the time complexity of the following code snippet.
read -p "Enter a number: " num
if [ "$num" -eq 1 ]; then
echo "Number is one"
elif [ "$num" -eq 2 ]; then
echo "Number is two"
else
echo "Number is something else"
fi
This script checks a number and prints a message based on its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one by one.
- How many times: At most, it checks each condition once in order.
Each input number causes the script to check conditions until one matches or all are checked.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 check (first condition matches) |
| 2 | 2 checks (first fails, second matches) |
| 3 | 2 checks (both conditions fail, else runs) |
Pattern observation: The number of checks grows linearly with how far down the conditions we go.
Time Complexity: O(n)
This means the time grows linearly with the number of conditions checked.
[X] Wrong: "If statements always run in constant time no matter how many conditions there are."
[OK] Correct: The script checks conditions one by one, so more conditions mean more checks and more time.
Understanding how condition checks add up helps you explain script efficiency clearly and confidently.
"What if we replaced the if-elif-else with a case statement? How would the time complexity change?"