0
0
Bash Scriptingscripting~5 mins

Exit codes ($?) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Exit codes ($?)
O(n)
Understanding Time Complexity

We want to understand how checking exit codes affects the time a script takes to run.

Specifically, how does the number of commands impact the time spent checking their exit codes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for file in *.txt; do
  cp "$file" /backup/
  if [ $? -ne 0 ]; then
    echo "Copy failed for $file"
  fi
done
    

This script copies all .txt files to a backup folder and checks the exit code after each copy to see if it succeeded.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that goes through each .txt file.
  • How many times: Once for each .txt file in the folder.
  • The exit code check [ $? -ne 0 ] runs once per file, right after the copy command.
How Execution Grows With Input

As the number of .txt files grows, the script runs the copy and exit code check for each file.

Input Size (n)Approx. Operations
10About 10 copies and 10 exit code checks
100About 100 copies and 100 exit code checks
1000About 1000 copies and 1000 exit code checks

Pattern observation: The total work grows directly with the number of files. Double the files, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows linearly with the number of files processed.

Common Mistake

[X] Wrong: "Checking the exit code is a separate step that doesn't add to the time complexity."

[OK] Correct: The exit code check runs every time inside the loop, so it adds work proportional to the number of files, affecting total time.

Interview Connect

Understanding how simple checks like exit codes add to script runtime helps you write efficient scripts and explain your reasoning clearly in interviews.

Self-Check

What if we removed the exit code check inside the loop? How would the time complexity change?