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?
Practice
trap in a bash script?Solution
Step 1: Understand the role of trap
Thetrapcommand is designed to catch signals or script exit events and run commands in response.Step 2: Compare options with trap's purpose
Options B, C, and D describe other bash features unrelated totrap. Only To run specific commands when the script exits or receives signals correctly describes its purpose.Final Answer:
To run specific commands when the script exits or receives signals -> Option CQuick Check:
trap runs commands on exit/signals = A [OK]
- Confusing trap with loops or functions
- Thinking trap declares variables
- Assuming trap runs commands continuously
cleanup function on script exit using trap?Solution
Step 1: Recall trap syntax for commands
The command(s) to run must be quoted as a string, followed by the signal or event name.Step 2: Check each option's syntax
trap 'cleanup' EXIT correctly quotes the command and uses the signalEXIT. trap EXIT cleanup places the signal before the command (wrong order). Options C and D use incorrect keywords like 'on'.Final Answer:
trap 'cleanup' EXIT -> Option DQuick Check:
trap 'command' SIGNAL = B [OK]
- Omitting quotes around commands
- Using 'on' keyword incorrectly
- Placing signal before command
#!/bin/bash
cleanup() {
echo "Cleaning up temp files"
}
trap 'cleanup' EXIT
echo "Script is running"
Solution
Step 1: Understand script flow
The script prints "Script is running" first, then exits.Step 2: Effect of trap on EXIT
On exit, thecleanupfunction runs, printing "Cleaning up temp files" after the first echo.Final Answer:
Script is running\nCleaning up temp files -> Option BQuick Check:
trap runs cleanup on exit, so both lines print [OK]
- Thinking trap runs before script output
- Expecting only cleanup message
- Ignoring trap on EXIT
#!/bin/bash
trap cleanup EXIT
cleanup() {
echo "Cleaning up"
}Solution
Step 1: Check trap command syntax
For simple function names likecleanup, quotes are not required around the command intrap.Step 2: Analyze script order and signals
Definingcleanupaftertrapis allowed because bash processes function definitions before executing traps.EXITis valid. No syntax errors present.Final Answer:
No error, script is correct -> Option AQuick Check:
unquoted function name OK, post-definition OK [OK]
- Thinking functions must be defined before trap
- Believing EXIT is an invalid signal
- Assuming quotes are required around simple commands
/tmp/mytempfile is deleted when your bash script exits, even if interrupted. Which trap command correctly achieves this?Solution
Step 1: Understand trap for multiple signals
To catch script exit and interruptions, use signals EXIT, INT, and TERM together.Step 2: Check syntax correctness
Commands must be quoted. trap 'rm -f /tmp/mytempfile' EXIT INT TERM quotes the command and lists valid signals. Options B misses quotes, C uses invalid signal ONEXIT, D uses invalid SIGNAL keyword.Final Answer:
trap 'rm -f /tmp/mytempfile' EXIT INT TERM -> Option AQuick Check:
trap 'command' SIGNALS with quotes = A [OK]
- Missing quotes around commands
- Using invalid signal names
- Not including INT and TERM for interrupts
Ready to prove it?
Pass the test and this pattern moves unknown
