0
0
Bash Scriptingscripting~5 mins

Custom exit codes (exit N) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom exit codes (exit N)
O(1)
Understanding Time Complexity

When using custom exit codes in bash scripts, it's important to understand how the script's running time changes as it executes commands.

We want to see how the script's steps grow when it uses exit codes to stop early or continue.

Scenario Under Consideration

Analyze the time complexity of the following bash script using custom exit codes.

#!/bin/bash
for i in {1..n}; do
  if [[ $i -eq 5 ]]; then
    exit 3  # Custom exit code
  fi
  echo "Processing $i"
done

This script loops from 1 to n, prints each number, but exits early with code 3 when i equals 5.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop iterating from 1 to n.
  • How many times: Up to 5 times because the script exits early at i=5.
How Execution Grows With Input

Because the script stops at i=5, the number of steps does not grow with n beyond 5.

Input Size (n)Approx. Operations
105 (stops early)
1005 (stops early)
10005 (stops early)

Pattern observation: The script runs a fixed number of steps regardless of input size because of the early exit.

Final Time Complexity

Time Complexity: O(1)

This means the script runs a constant number of steps no matter how big n is, due to the early exit.

Common Mistake

[X] Wrong: "The script always runs n times because the loop goes from 1 to n."

[OK] Correct: The script stops early at i=5 using exit, so it does not complete all n iterations.

Interview Connect

Understanding how early exits affect script runtime helps you reason about efficiency and control flow in real scripts.

Self-Check

What if the exit condition was changed to i equals n instead of 5? How would the time complexity change?