0
0
Bash Scriptingscripting~5 mins

trap for cleanup on exit in Bash Scripting

Choose your learning style9 modes available
Introduction
Use trap to run cleanup code automatically when your script ends or is interrupted. This helps keep things tidy and safe.
You want to delete temporary files when your script finishes or stops.
You need to close network connections or release resources before exiting.
You want to show a goodbye message or log info when the script ends.
You want to handle user pressing Ctrl+C to stop the script safely.
Syntax
Bash Scripting
trap 'commands_to_run' signals
commands_to_run is the code you want to execute on exit or signal.
signals are events like EXIT (script ends) or INT (Ctrl+C).
Examples
Runs 'echo Cleanup done' when the script finishes normally or by exit.
Bash Scripting
trap 'echo Cleanup done' EXIT
Deletes a temporary file when the script ends.
Bash Scripting
trap 'rm -f /tmp/tempfile' EXIT
Prints a message and exits when you press Ctrl+C.
Bash Scripting
trap 'echo Interrupted; exit' INT
Sample Program
This script creates a temp file, sets a trap to delete it when the script ends, then does some work. The cleanup runs automatically on exit.
Bash Scripting
#!/bin/bash

# Create a temp file
tempfile="/tmp/mytempfile.txt"
touch "$tempfile"
echo "Temp file created: $tempfile"

# Define cleanup function
cleanup() {
  echo "Cleaning up..."
  rm -f "$tempfile"
  echo "Cleanup done."
}

# Set trap to call cleanup on script exit
trap cleanup EXIT

# Simulate work
echo "Doing some work..."
sleep 2

echo "Script finished."
OutputSuccess
Important Notes
The EXIT signal runs the trap code no matter how the script ends (normal exit, error, or Ctrl+C).
You can define a function for cleanup and call it in trap for cleaner code.
Use trap to avoid leaving temporary files or resources behind.
Summary
trap runs commands when your script exits or receives signals.
Use it to clean up files, close connections, or show messages.
It helps keep your system clean and your scripts safe.