Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Shell Script Dictionary
  3. trap

trap

Since: POSIX(sh互換)

In shell scripts, trap is a mechanism for registering commands to execute when a signal or exit event is received. The syntax is trap 'command' signal_name, and the registered command runs the moment the script receives the specified signal. The most common use case is cleanup processing — deleting temporary files just before the script exits or is interrupted. The four signals EXIT, INT, TERM, and HUP cover virtually all practical scenarios.

Signal list

Signal nameNumberWhen it occursDescription
EXITWhen the script exitsRuns in all cases: normal exit, exit call, or error exit. The most common target for registering cleanup logic.
INT2When Ctrl+C is pressedTriggered when the user manually interrupts the script. Useful for displaying a message or cleaning up on early exit.
TERM15When a termination request is received via the kill commandA normal stop request from the OS or a job scheduler. Sent with kill -15 PID or simply kill PID.
HUP1When the terminal is disconnectedTriggered when an SSH session drops or a terminal window is closed. Also used to reload daemon process configuration.
ERRWhen a command returns a non-zero exit statusUsed in combination with set -e to output detailed error logs on failure.

trap syntax

SyntaxDescription
trap 'command' signalRegisters a command to run when the signal is received. Multiple signals can be listed separated by spaces.
trap cleanup_function EXIT INT TERM HUPRegisters the same function for multiple signals. This is the standard pattern used in practical scripts.
trap '' signalIgnores the signal (leave the single-quoted string empty).
trap - signalRemoves the registration and restores the default behavior.
# -----------------------------------------------
#  trap syntax examples
# -----------------------------------------------

# EXIT: runs whenever the script exits
trap 'echo "Script exited"' EXIT

# INT: runs when interrupted with Ctrl+C
trap 'echo "Interrupted"; exit 130' INT

# Register the same handler for multiple signals
trap 'echo "Stop signal received"; exit 1' TERM HUP

# Register a function (improves readability)
cleanup() {
    echo "Running cleanup"
}
trap cleanup EXIT INT TERM HUP

# Ignore a signal
trap '' INT    # Disable Ctrl+C

# Remove the registration and restore default behavior
trap - INT

Temporary file cleanup pattern

In scripts that use temporary files, it is standard practice to write trap cleanup EXIT INT TERM HUP near the top so that files are not left behind regardless of whether the script exits normally, is interrupted with Ctrl+C, or is stopped with kill. Specifying only EXIT is sufficient in most cases, but adding INT, TERM, and HUP makes cleanup more reliable.

# -----------------------------------------------
#  Temporary file cleanup pattern (skeleton)
# -----------------------------------------------

#!/bin/bash
set -euo pipefail

# Create a temporary file safely with mktemp
TMPFILE=$(mktemp /tmp/script_XXXXXX)

# -----------------------------------------------
#  Cleanup function
#  Called on exit via EXIT / INT / TERM / HUP
# -----------------------------------------------
cleanup() {
    # Delete only if the file exists (guards against double execution)
    if [ -f "${TMPFILE}" ]; then
        rm -f "${TMPFILE}"
        echo "Temporary file removed: ${TMPFILE}" >&2
    fi
}

# Register trap near the top of the script
trap cleanup EXIT INT TERM HUP

# -----------------------------------------------
#  Main processing (use TMPFILE here)
# -----------------------------------------------
echo "Processing..." > "${TMPFILE}"
cat "${TMPFILE}"

# cleanup is called automatically via the EXIT signal

Sample code

eva_trap_cleanup.sh
#!/bin/bash
# -----------------------------------------------
#  Writes sortie logs for 5 Evangelion pilots
#  to a temporary file and removes it reliably with trap
# -----------------------------------------------

set -euo pipefail

# -----------------------------------------------
#  Create a temporary file safely
# -----------------------------------------------
TMPFILE=$(mktemp /tmp/nerv_log_XXXXXX)

echo "=== NERV Sortie Log System Starting ==="
echo "Temporary file: ${TMPFILE}"
echo ""

# -----------------------------------------------
#  Cleanup function
#  Called on EXIT / INT / TERM / HUP
# -----------------------------------------------
cleanup() {
    echo "" >&2
    echo "[cleanup] Removing temporary file: ${TMPFILE}" >&2
    rm -f "${TMPFILE}"
    echo "[cleanup] Done. NERV classified data protected." >&2
}

# Set trap for the entire script
trap cleanup EXIT INT TERM HUP

# -----------------------------------------------
#  Write pilot sortie data to the temporary file
# -----------------------------------------------
{
    echo "# NERV Sortie Log — $(date '+%Y-%m-%d %H:%M:%S')"
    echo "Ikari Shinji,Unit-01,3rd Angel,destroyed"
    echo "Ayanami Rei,Unit-00,5th Angel,destroyed"
    echo "Soryu Asuka Langley,Unit-02,7th Angel,destroyed"
    echo "Nagisa Kaworu,17th Angel,—,merged"
    echo "Makinami Mari Illustrious,Provisional Unit-05,10th Angel,destroyed"
} > "${TMPFILE}"

echo "--- Sortie Log (temporary file contents) ---"
cat "${TMPFILE}"
echo ""

# -----------------------------------------------
#  Summarize the log
# -----------------------------------------------
total=$(grep -c "," "${TMPFILE}")
destroyed=$(grep -c "destroyed" "${TMPFILE}")

echo "--- Summary ---"
echo "Pilots sortied : ${total}"
echo "Angels destroyed : ${destroyed}"
echo ""
echo "=== Processing complete ==="

# cleanup is called automatically via the EXIT signal
$ chmod +x eva_trap_cleanup.sh
$ ./eva_trap_cleanup.sh
=== NERV Sortie Log System Starting ===
Temporary file: /tmp/nerv_log_Xk3m9q

--- Sortie Log (temporary file contents) ---
# NERV Sortie Log — 2026-03-27 10:00:00
Ikari Shinji,Unit-01,3rd Angel,destroyed
Ayanami Rei,Unit-00,5th Angel,destroyed
Soryu Asuka Langley,Unit-02,7th Angel,destroyed
Nagisa Kaworu,17th Angel,—,merged
Makinami Mari Illustrious,Provisional Unit-05,10th Angel,destroyed

--- Summary ---
Pilots sortied : 5
Angels destroyed : 4

=== Processing complete ===

[cleanup] Removing temporary file: /tmp/nerv_log_Xk3m9q
[cleanup] Done. NERV classified data protected.
eva_trap_int.sh
#!/bin/bash
# -----------------------------------------------
#  Detects Ctrl+C (INT signal) and safely
#  interrupts pilot name processing
# -----------------------------------------------

set -uo pipefail

# -----------------------------------------------
#  Holds the name of the pilot currently being processed
# -----------------------------------------------
CURRENT_PILOT=""

# -----------------------------------------------
#  INT signal handler
#  Called when Ctrl+C is pressed
# -----------------------------------------------
handle_int() {
    echo "" >&2
    echo "[interrupted] Ctrl+C detected." >&2
    if [ -n "${CURRENT_PILOT}" ]; then
        echo "[interrupted] Aborting processing for ${CURRENT_PILOT}." >&2
    fi
    echo "[interrupted] Emergency alert sent to NERV Operations." >&2
    exit 130    # Convention: 128 + 2 (INT) = 130
}

# -----------------------------------------------
#  EXIT signal handler (records the reason for exit)
# -----------------------------------------------
handle_exit() {
    local code=$?
    if [ "${code}" -eq 130 ]; then
        echo "[exit] Interrupted exit (status: ${code})" >&2
    elif [ "${code}" -eq 0 ]; then
        echo "[exit] Normal exit (status: ${code})" >&2
    else
        echo "[exit] Abnormal exit (status: ${code})" >&2
    fi
}

trap handle_int  INT
trap handle_exit EXIT

# -----------------------------------------------
#  Generate evaluation reports for 5 pilots
#  Each pilot takes 1 second to process (interruptible with Ctrl+C)
# -----------------------------------------------
pilots=(
    "Ikari Shinji"
    "Ayanami Rei"
    "Soryu Asuka Langley"
    "Nagisa Kaworu"
    "Makinami Mari Illustrious"
)

echo "=== Pilot Evaluation Report Generation Started ==="
echo "(Press Ctrl+C to interrupt)"
echo ""

for pilot in "${pilots[@]}"; do
    CURRENT_PILOT="${pilot}"
    echo "Processing: ${pilot} ..."
    sleep 1    # Simulates a heavy operation
    echo "  Done: report generated for ${pilot}"
done

CURRENT_PILOT=""
echo ""
echo "=== All pilot reports generated successfully ==="
# When run to completion
$ chmod +x eva_trap_int.sh
$ ./eva_trap_int.sh
=== Pilot Evaluation Report Generation Started ===
(Press Ctrl+C to interrupt)

Processing: Ikari Shinji ...
  Done: report generated for Ikari Shinji
Processing: Ayanami Rei ...
  Done: report generated for Ayanami Rei
Processing: Soryu Asuka Langley ...
  Done: report generated for Soryu Asuka Langley
Processing: Nagisa Kaworu ...
  Done: report generated for Nagisa Kaworu
Processing: Makinami Mari Illustrious ...
  Done: report generated for Makinami Mari Illustrious

=== All pilot reports generated successfully ===
[exit] Normal exit (status: 0)

# When Ctrl+C is pressed during Ayanami Rei's processing
$ ./eva_trap_int.sh
=== Pilot Evaluation Report Generation Started ===
(Press Ctrl+C to interrupt)

Processing: Ikari Shinji ...
  Done: report generated for Ikari Shinji
Processing: Ayanami Rei ...
^C
[interrupted] Ctrl+C detected.
[interrupted] Aborting processing for Ayanami Rei.
[interrupted] Emergency alert sent to NERV Operations.
[exit] Interrupted exit (status: 130)

Summary

The trap built-in command in shell scripts registers commands or functions to execute when a signal or exit event is received. EXIT is guaranteed to run whenever the script exits, making it the standard target for registering temporary file deletion and working directory cleanup. Registering INT (Ctrl+C), TERM (kill), and HUP (terminal disconnect) together ensures cleanup runs regardless of how the script exits. The recommended pattern for robust scripts is to create temporary files with mktemp, store the path in a variable, and write trap cleanup EXIT INT TERM HUP near the top of the script. For exit status handling, see exit / return (exit status); the same page also covers set -e for error control.

If you find any errors or copyright issues, please .