0
0
Bash Scriptingscripting~5 mins

set -e for exit on error in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: set -e for exit on error
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated commands that affect execution time.

  • Primary operation: The for loop running grep on each file.
  • How many times: Once for each .txt file in the folder.
How Execution Grows With Input

As the number of text files grows, the script runs grep more times.

Input Size (n)Approx. Operations
10About 10 grep calls
100About 100 grep calls
1000About 1000 grep calls

Pattern observation: The number of operations grows directly with the number of files.

Final Time Complexity

Time Complexity: O(n)

This means the script's running time grows linearly with the number of files processed.

Common Mistake

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

Interview Connect

Understanding how error handling affects script flow and time helps you write reliable scripts and explain your reasoning clearly in interviews.

Self-Check

What if we removed set -e and let the script continue even after errors? How would the time complexity change?