Exit codes ($?) in Bash Scripting - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop 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.
As the number of .txt files grows, the script runs the copy and exit code check for each file.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 copies and 10 exit code checks |
| 100 | About 100 copies and 100 exit code checks |
| 1000 | About 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.
Time Complexity: O(n)
This means the time to run grows linearly with the number of files processed.
[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.
Understanding how simple checks like exit codes add to script runtime helps you write efficient scripts and explain your reasoning clearly in interviews.
What if we removed the exit code check inside the loop? How would the time complexity change?