-
-
Notifications
You must be signed in to change notification settings - Fork 1
Linux trap Guide
Mattscreative edited this page Dec 5, 2025
·
2 revisions
Complete beginner-friendly guide to trap on Linux, covering Arch Linux, CachyOS, and other distributions including signal handling, cleanup on exit, and script error handling.
trap catches signals and executes commands.
Uses:
- Signal handling: Handle signals
- Cleanup: Clean up on exit
- Error handling: Handle errors
- Script safety: Make scripts safer
Why it matters:
- Cleanup: Ensure cleanup happens
- Error handling: Handle errors gracefully
- Script safety: Make scripts robust
Basic usage:
# Trap signal
trap 'command' SIGNAL
# Executes command on signalCommon signals:
# Trap EXIT
trap 'cleanup' EXIT
# Trap INT (Ctrl+C)
trap 'echo "Interrupted"' INT
# Trap TERM
trap 'cleanup' TERMTrap several:
# Multiple signals
trap 'cleanup' INT TERM EXIT
# Handles all threeIgnore signal:
# Ignore signal
trap '' INT
# Empty string = ignoreIn scripts:
#!/bin/bash
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
}
trap cleanup EXIT
# Script continues
# Cleanup runs on exitCheck syntax:
# Verify trap syntax
trap -p
# Shows current trapsThis guide covered trap usage, signal handling, and cleanup for Arch Linux, CachyOS, and other distributions.
- Bash Scripting Guide - Scripting
- kill Guide - Send signals
-
trap Documentation:
man trap
This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.