What if your script could clean up its mess no matter how it ends?
Why trap for cleanup on exit in Bash Scripting? - Purpose & Use Cases
Imagine you run a script that creates temporary files or starts background tasks. If you stop the script suddenly or it crashes, those files or tasks stay behind, cluttering your system.
Manually cleaning up after every possible exit is hard. You might forget some cases, or the script might be interrupted unexpectedly. This leads to leftover files, wasted space, or stuck processes.
The trap command lets your script catch exit signals and run cleanup code automatically. This means no matter how the script ends, it tidies up after itself.
rm temp.txt
# but if script is stopped early, temp.txt staystrap 'rm -f temp.txt' INT TERM EXIT # temp.txt is removed automatically on any exit
You can write scripts that always clean up safely, making your system neat and your scripts reliable.
A backup script creates a temp folder to store files. Using trap, it deletes the folder even if you press Ctrl+C to stop it.
Manual cleanup is unreliable and error-prone.
trap runs cleanup code on script exit automatically.
This keeps your system clean and scripts dependable.
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
