trap

shell scriptingLinux/Unix
The trap command is one of the most frequently used commands in Linux/Unix-like operating systems. trap Set up signal handlers in shell scripts

Quick Reference

Command Name:

trap

Category:

shell scripting

Platform:

Linux/Unix

Basic Usage:

trap [options] [arguments]

Common Use Cases

    Syntax

    trap [OPTIONS] [[ARG] SIGNAL...]

    Options

    Option Description
    -l List signal names and their corresponding numbers
    -p Display the trap commands associated with each SIGNAL
    --help Display help information and exit
    --version Output version information and exit
    Common Signal Names
    SIGHUP (1) Hangup detected on controlling terminal or death of controlling process
    SIGINT (2) Interrupt from keyboard (Ctrl+C)
    SIGQUIT (3) Quit from keyboard (Ctrl+\)
    SIGILL (4) Illegal instruction
    SIGTRAP (5) Trace/breakpoint trap
    SIGABRT (6) Abort signal from abort(3)
    SIGKILL (9) Kill signal (cannot be caught or ignored)
    SIGTERM (15) Termination signal
    SIGSTOP (17,19,23) Stop process (cannot be caught or ignored)
    SIGTSTP (18,20,24) Stop typed at terminal (Ctrl+Z)
    SIGCONT (19,18,25) Continue if stopped
    SIGWINCH (28,28,26) Window resize signal
    EXIT (0) Exit from shell (not a real signal, but often used with trap)
    ERR Execute on error (not a real signal, Bash-specific)
    DEBUG Execute before every command (not a real signal, Bash-specific)

    Examples

    How to Use These Examples

    The examples below show common ways to use the trap command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.

    # Basic Examples Basic
    # Display a message when the script is interrupted with Ctrl+C trap "echo 'Script interrupted'" SIGINT
    # Run cleanup function when the script exits trap cleanup EXIT
    # Ignore keyboard interrupt (Ctrl+C) trap "" SIGINT
    # Advanced Examples Advanced
    # Clean up temporary files on script exit # !/bin/bash
    TEMPFILE=$(mktemp) cleanup() { echo "Cleaning up..." rm -f "$TEMPFILE" } trap cleanup EXIT # Rest of script... # Handle multiple signals trap "echo 'Terminating...'; exit" SIGINT SIGTERM # Restore default behavior for a signal trap - SIGINT # Create a simple menu with a timeout #!/bin/bash timeout_handler() { echo "Timeout reached, exiting..." exit 1 } trap timeout_handler SIGALRM echo "Enter your choice (10 seconds):" read -t 10 choice || timeout_handler # Detect window resize in a terminal application trap 'echo "Terminal resized to $(tput cols)x$(tput lines)"' SIGWINCH # Prevent script from being interrupted trap "" SIGINT SIGTERM SIGTSTP # Log all termination attempts trap 'echo "Received signal $? at $(date)" >> /tmp/script_log.txt' SIGINT SIGTERM # Execute custom code before script suspension trap 'echo "Suspending script..."; sleep 1' SIGTSTP # Create a debug trap that shows each command before execution trap 'echo "DEBUG: $BASH_COMMAND"' DEBUG # Use ERR trap to catch command failures trap 'echo "Error on line $LINENO" >&2' ERR

    Try It Yourself

    Practice makes perfect! The best way to learn is by trying these examples on your own system with real files.

    Understanding Syntax

    Pay attention to the syntax coloring: commands, options, and file paths are highlighted differently.

    Notes

    The `trap` command is a fundamental tool in shell scripting that allows you to specify commands to be executed when a shell script receives specific signals. This is essential for handling unexpected events, performing cleanup operations, and ensuring graceful termination of scripts. In Unix-like systems, signals are a form of inter-process communication used to notify processes about specific events. These events can range from user-initiated actions (like pressing Ctrl+C to interrupt a program) to system events (like a process trying to access an invalid memory address). When a process receives a signal, it can ignore it, handle it with a custom handler, or perform the default action associated with that signal (which is often termination). The `trap` command sets up these custom handlers within shell scripts. The basic syntax is `trap 'commands' signals`, where `commands` is a string containing shell commands to execute when any of the specified `signals` are received. One of the most common uses of `trap` is for cleanup operations. For example, many scripts create temporary files during execution, and it's important to remove these files even if the script is terminated unexpectedly. By using `trap 'rm -f /tmp/tempfile' EXIT`, you ensure the temporary file is removed when the script exits, regardless of how it exits. Some important signals commonly handled with `trap` include: - `SIGINT` (2): Sent when the user presses Ctrl+C, typically used to interrupt a program - `SIGTERM` (15): The default signal sent by commands like `kill`, asking a process to terminate gracefully - `SIGHUP` (1): Historically sent when a terminal connection was lost; now often used to signal configuration reloads - `EXIT` (not a real signal): A pseudo-signal recognized by shells that triggers when the script exits for any reason In addition to setting up handlers, `trap` can be used to: - List available signals with `trap -l` - Display current trap settings with `trap -p` - Reset a signal to its default behavior with `trap - SIGNAL` - Ignore a signal completely with `trap '' SIGNAL` Bash also supports some special pseudo-signals not available in all shells: - `ERR`: Triggered whenever a command returns a non-zero exit status - `DEBUG`: Triggered before each command is executed - `RETURN`: Triggered when a function or sourced script completes It's worth noting that some signals, particularly `SIGKILL` (9) and `SIGSTOP`, cannot be caught or ignored. This ensures that system administrators always have a way to terminate or stop processes that might otherwise refuse to respond to normal termination signals. Effective use of `trap` is a hallmark of robust shell scripts, as it helps ensure resources are properly managed and scripts behave predictably even in unexpected situations.

    Related Commands

    These commands are frequently used alongside trap or serve similar purposes:

    Use Cases

    Learn By Doing

    The best way to learn Linux commands is by practicing. Try out these examples in your terminal to build muscle memory and understand how the trap command works in different scenarios.

    $ trap
    View All Commands