0
0
Bash Scriptingscripting~15 mins

trap for cleanup on exit in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using trap for Cleanup on Exit in Bash
📖 Scenario: You are writing a bash script that creates a temporary file to store some data. To keep your system clean, you want to make sure this temporary file is deleted automatically when the script finishes or if it is interrupted.
🎯 Goal: Build a bash script that creates a temporary file, sets up a trap to delete this file when the script exits, and then prints a message confirming the cleanup.
📋 What You'll Learn
Create a variable tempfile with the value /tmp/mytempfile.txt
Set up a trap command to delete $tempfile on script exit
Create the temporary file using touch
Print Cleanup done! after the file is deleted
💡 Why This Matters
🌍 Real World
Scripts often create temporary files or resources that must be cleaned up to avoid clutter or security risks. Using trap ensures cleanup happens even if the script is interrupted.
💼 Career
Knowing how to use trap for cleanup is important for system administrators, DevOps engineers, and anyone writing reliable shell scripts that manage temporary resources.
Progress0 / 4 steps
1
Create the temporary file variable
Create a variable called tempfile and set it to the string /tmp/mytempfile.txt.
Bash Scripting
Need a hint?

Use tempfile=/tmp/mytempfile.txt to assign the path.

2
Set up the trap for cleanup
Add a trap command that runs rm -f "$tempfile" and then echo "Cleanup done!" when the script exits.
Bash Scripting
Need a hint?

Use trap 'rm -f "$tempfile"; echo "Cleanup done!"' EXIT to run commands on exit.

3
Create the temporary file
Use the touch command to create the file at the path stored in tempfile.
Bash Scripting
Need a hint?

Use touch "$tempfile" to create the file.

4
Test the cleanup on exit
Run the script and observe that when it finishes, it prints Cleanup done! and the temporary file is deleted.
Bash Scripting
Need a hint?

Run the script normally. The message Cleanup done! should appear when it exits.