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.txtSet up a
trap command to delete $tempfile on script exitCreate the temporary file using
touchPrint
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