0
0
Bash Scriptingscripting~5 mins

if-elif-else in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: if-elif-else
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each input number causes the script to check conditions until one matches or all are checked.

Input Size (n)Approx. Operations
11 check (first condition matches)
22 checks (first fails, second matches)
32 checks (both conditions fail, else runs)

Pattern observation: The number of checks grows linearly with how far down the conditions we go.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of conditions checked.

Common Mistake

[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.

Interview Connect

Understanding how condition checks add up helps you explain script efficiency clearly and confidently.

Self-Check

"What if we replaced the if-elif-else with a case statement? How would the time complexity change?"