set -e for exit on error in Bash Scripting - Time & Space Complexity
We want to understand how using set -e affects the running time of a bash script.
Specifically, does it change how long the script runs as input grows?
Analyze the time complexity of the following bash script snippet.
#!/bin/bash
set -e
for file in *.txt; do
grep "pattern" "$file"
done
This script searches for a pattern in all text files and stops immediately if any command fails.
Look for loops or repeated commands that affect execution time.
- Primary operation: The
forloop runninggrepon each file. - How many times: Once for each
.txtfile in the folder.
As the number of text files grows, the script runs grep more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 grep calls |
| 100 | About 100 grep calls |
| 1000 | About 1000 grep calls |
Pattern observation: The number of operations grows directly with the number of files.
Time Complexity: O(n)
This means the script's running time grows linearly with the number of files processed.
[X] Wrong: "Using set -e makes the script run faster because it stops early."
[OK] Correct: While set -e stops on errors, it does not speed up successful runs. The time still depends on how many files are processed before an error or completion.
Understanding how error handling affects script flow and time helps you write reliable scripts and explain your reasoning clearly in interviews.
What if we removed set -e and let the script continue even after errors? How would the time complexity change?