trap for cleanup on exit in Bash Scripting - Time & Space Complexity
When using trap in bash to clean up on exit, it is important to understand how the script's running time changes as input grows.
We want to see how the cleanup action affects the total work done by the script.
Analyze the time complexity of the following bash script using trap for cleanup.
#!/bin/bash
trap 'echo "Cleaning up..."; rm -f temp_file.txt' EXIT
for i in $(seq 1 $1); do
echo "Line $i" >> temp_file.txt
sleep 0.01
done
This script writes lines to a temporary file in a loop and uses trap to delete the file when the script exits.
Look at what repeats as input size changes.
- Primary operation: The
forloop writing lines to the file. - How many times: Exactly
ntimes, wherenis the input argument. - Cleanup operation: The
trapruns once on exit, deleting the file.
As the input number n grows, the loop runs more times, but the cleanup runs only once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes + 1 cleanup |
| 100 | 100 writes + 1 cleanup |
| 1000 | 1000 writes + 1 cleanup |
Pattern observation: The main work grows with n, but cleanup cost stays the same.
Time Complexity: O(n)
This means the script's running time grows linearly with the number of lines written, while cleanup cost is constant.
[X] Wrong: "The cleanup inside trap runs every loop iteration, so it adds to the loop's time."
[OK] Correct: The trap command runs only once when the script exits, not during the loop, so it does not multiply with input size.
Understanding how cleanup commands run helps you write scripts that manage resources well without slowing down your main work.
What if the cleanup command inside trap also looped over n items? How would the time complexity change?