Custom exit codes (exit N) in Bash Scripting - Time & Space 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.
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 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.
Because the script stops at i=5, the number of steps does not grow with n beyond 5.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 (stops early) |
| 100 | 5 (stops early) |
| 1000 | 5 (stops early) |
Pattern observation: The script runs a fixed number of steps regardless of input size because of the early exit.
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.
[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.
Understanding how early exits affect script runtime helps you reason about efficiency and control flow in real scripts.
What if the exit condition was changed to i equals n instead of 5? How would the time complexity change?