Skip to content

Linux trap Guide

Mattscreative edited this page Dec 5, 2025 · 2 revisions

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

  1. Understanding trap
  2. trap Basics
  3. Signal Handling
  4. Cleanup on Exit
  5. Troubleshooting

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


This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.

Clone this wiki locally