0
0
Bash Scriptingscripting~5 mins

if-then-fi structure in Bash Scripting - Time & Space Complexity

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

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

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

The script checks the condition once, no matter the input size.

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 script runs in constant time, doing the same amount of work no matter the input.

Common Mistake

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

Interview Connect

Understanding that simple condition checks run in constant time helps you explain script efficiency clearly and confidently.

Self-Check

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