> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Bash Signal Trap

The `trap` command is a POSIX-compliant shell builtin that allows a Bash script to intercept system signals and shell-specific events, executing a predefined command string or function (the handler) when the specified signal is delivered to the shell process. It provides a mechanism for asynchronous event handling within the synchronous execution flow of a script.

```bash theme={"dark"}
trap [-lp] [[arg] signal_spec ...]
```

## Syntax Breakdown

* **`arg`**: The command string or function name to execute when the signal is caught.
* **`signal_spec`**: The target signal. This can be a standard OS signal name (e.g., `INT`, `TERM`), a signal number (e.g., `2`, `15`), or a shell pseudo-signal (e.g., `EXIT`, `ERR`). For standard OS signals, the `SIG` prefix is optional (e.g., `SIGINT` and `INT` are equivalent). The `SIG` prefix must *not* be used with shell pseudo-signals (e.g., `SIGEXIT` is invalid).
* **`-p`**: Prints the currently installed traps in a format that can be reused as input.
* **`-l`**: Prints a list of all supported signal names and their corresponding numeric values (maps to the OS `signal.h`).

## Handler Evaluation and Quoting

The command string provided to `arg` is parsed twice by the shell: once when the `trap` is registered, and again when the signal is caught and the handler is invoked.

* **Single Quotes (`'...'`)**: Delays variable expansion until the signal is caught.
* **Double Quotes (`"..."`)**: Expands variables immediately at the time the trap is registered.

```bash theme={"dark"}

# Evaluates $VAR when SIGINT is received
trap 'echo $VAR' SIGINT


# Evaluates $VAR immediately; the handler executes the static string
trap "echo $VAR" SIGINT
```

## Modifying Signal Disposition

Beyond executing commands, `trap` alters the default disposition of signals:

**Ignoring a Signal:**
Passing an empty string (`''` or `""`) as the `arg` instructs the shell to completely ignore the specified signal.

```bash theme={"dark"}
trap '' SIGTERM
```

**Restoring Default Behavior:**
Passing a dash (`-`) as the `arg` resets the specified signals to their default OS or shell disposition. Omitting `arg` entirely also resets the signal, but its behavior depends on the arguments provided. If the first argument is a valid signal number (e.g., `trap 2 15`), Bash treats it as a `signal_spec` and resets all specified numeric signals. However, if multiple arguments are provided without a dash and the first argument is a signal *name* (e.g., `trap INT TERM`), Bash interprets the first argument (`INT`) as the `arg` (the command to execute) and applies it to the subsequent signals (`TERM`). Using a dash is the safest way to reset multiple signals by name.

```bash theme={"dark"}

# Resets a single signal by name
trap INT


# Resets multiple signals by number
trap 2 15


# Resets multiple signals by name safely using a dash
trap - INT TERM
```

## Pseudo-Signals

The shell supports intercepting internal state transitions as pseudo-signals. While `EXIT` is a standard POSIX feature, Bash extends this functionality with additional pseudo-signals:

* **`EXIT` (or `0`)**: A POSIX-standard pseudo-signal invoked when the shell process terminates, regardless of whether the termination was successful or caused by an error.
* **`ERR`**: A Bash extension invoked whenever a pipeline, list, or compound command returns a non-zero exit status. Its behavior is strictly bound by the same rules as the `set -e` (`errexit`) option.
* **`DEBUG`**: A Bash extension invoked immediately before every simple command, `for` command, `case` command, `select` command, or arithmetic `for` command is executed.
* **`RETURN`**: A Bash extension invoked when a shell function or a script executed with the `.` or `source` builtins finishes executing.

## Execution Context and Inheritance

* **Scope**: The handler executes in the current shell environment. If the handler is a function, it shares the variable scope and execution context of the script at the exact moment of interruption.
* **Subshells**: Standard signal traps defined in a parent shell are *not* inherited by subshells (e.g., command substitutions, background processes).
* **Pseudo-Signal Inheritance**: By default, the Bash-specific `ERR`, `DEBUG`, and `RETURN` traps are not inherited by shell functions, command substitutions, or subshells. To force inheritance into these contexts, specific shell options must be enabled:
  * `set -E` (or `set -o errtrace`): Inherits the `ERR` trap.
  * `set -T` (or `set -o functrace`): Inherits the `DEBUG` and `RETURN` traps.
* **Ignored Signals**: Unlike active traps, signals that are explicitly ignored (`trap '' SIG`) *are* inherited by child processes.
* **Signal Queuing**: Standard POSIX signals are tracked via a bitmask in the kernel, meaning they are not queued. If multiple signals of the same type are delivered while the shell is busy executing a foreground command, the kernel simply sets the corresponding pending flag. Once the foreground command completes, the shell detects that the pending flag is set and executes the trap handler exactly once, regardless of how many times the signal was sent.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Bash Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
