0
0
Bash Scriptingscripting~5 mins

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

Choose your learning style9 modes available
Time Complexity: if-then-else
O(1)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single if-then-else condition check
  • How many times: Exactly once per script run
How Execution Grows With Input

The script runs the if-then-else check once no matter what the input number is.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations stays the same regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if-then-else does not grow with input size; it stays constant.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we added a loop inside the if-then-else that runs n times? How would the time complexity change?"