Linux trap Guide - ryzendew/Linux-Tips-and-Tricks GitHub Wiki
Linux trap Guide
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.
Table of Contents
Understanding trap
What is trap?
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
trap Basics
Trap Signal
Basic usage:
# Trap signal
trap 'command' SIGNAL
# Executes command on signal
Common Signals
Common signals:
# Trap EXIT
trap 'cleanup' EXIT
# Trap INT (Ctrl+C)
trap 'echo "Interrupted"' INT
# Trap TERM
trap 'cleanup' TERM
Signal Handling
Multiple Signals
Trap several:
# Multiple signals
trap 'cleanup' INT TERM EXIT
# Handles all three
Ignore Signal
Ignore signal:
# Ignore signal
trap '' INT
# Empty string = ignore
Cleanup on Exit
Cleanup Function
In scripts:
#!/bin/bash
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
}
trap cleanup EXIT
# Script continues
# Cleanup runs on exit
Troubleshooting
trap Not Working
Check syntax:
# Verify trap syntax
trap -p
# Shows current traps
Summary
This guide covered trap usage, signal handling, and cleanup for Arch Linux, CachyOS, and other distributions.
Next Steps
- 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.