0
0
Bash Scriptingscripting~10 mins

trap for cleanup on exit in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - trap for cleanup on exit
Start Script
Set trap for EXIT
Run main commands
Script ends or interrupted
Trap triggers cleanup function
Cleanup actions run
Exit script
The script sets a trap to run cleanup code when it exits normally or is interrupted.
Execution Sample
Bash Scripting
cleanup() {
  echo "Cleaning up..."
}
trap cleanup EXIT

echo "Script running"
This script sets a trap to run the cleanup function when the script exits.
Execution Table
StepActionOutputTrap TriggeredNotes
1Define cleanup functionNoFunction ready but not run
2Set trap on EXIT to cleanupNoTrap set for script exit
3Print 'Script running'Script runningNoMain script running
4Script ends normallyYesTrap triggers cleanup
5Run cleanup functionCleaning up...YesCleanup runs on exit
💡 Script ends, trap on EXIT triggers cleanup function
Variable Tracker
VariableStartAfter Step 3After Step 5
cleanup functionDefinedDefinedExecuted
Key Moments - 2 Insights
Why does the cleanup function run even though we never call it explicitly?
Because the trap command links the cleanup function to the EXIT signal, so it runs automatically when the script ends (see execution_table step 4 and 5).
What happens if the script is interrupted with Ctrl+C?
The EXIT trap still triggers the cleanup function, ensuring cleanup runs on interruption as well.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 3?
ANothing
B"Cleaning up..."
C"Script running"
D"Exit script"
💡 Hint
Check the Output column at step 3 in the execution_table.
At which step does the cleanup function run?
AStep 2
BStep 5
CStep 3
DStep 1
💡 Hint
Look at the Trap Triggered and Output columns in the execution_table.
If we remove the trap command, what changes in the execution?
ACleanup function never runs unless called explicitly
BCleanup function runs automatically on exit
CScript prints "Cleaning up..." before "Script running"
DScript will not print anything
💡 Hint
Refer to the role of trap in linking cleanup to script exit in the concept_flow.
Concept Snapshot
trap command links signals to functions
Use 'trap cleanup EXIT' to run cleanup on script exit
Cleanup runs on normal exit or interruption
Ensures resources are freed or temp files removed
No explicit call needed for cleanup function
Full Transcript
This script defines a cleanup function and sets a trap to run it when the script exits. The trap command listens for the EXIT signal, which happens when the script finishes or is interrupted. When the script runs, it prints 'Script running'. When the script ends, the trap triggers the cleanup function, which prints 'Cleaning up...'. This ensures cleanup code always runs without needing explicit calls.