Terminal · intermediate

Signals and traps

A signal is an asynchronous notification delivered to a process, while a shell trap arranges for shell code to run when selected signals or synthetic events such as EXIT occur.

Why it matters

Scripts use traps to remove temporary resources and respond predictably to interruption, but signals are notifications rather than guaranteed transactional cleanup.

Mental model

How to reason about signals and traps

The operating system marks a signal pending; at an allowed point the process performs the default action, ignores it, or runs an installed handler, while uncatchable signals bypass cleanup.

Analogy

A signal is an interrupt bell with a predefined default response; a trap installs a custom response card, but a sudden power cut still bypasses the card entirely.

Examples

See the boundary, not just the happy path

Worked example · Clean up on shell exit

tmp=$(mktemp -d) || exit; trap 'rm -rf -- "$tmp"' EXIT

After successful creation, the EXIT trap removes the specific temporary directory on normal exit and many handled failure paths; the captured variable belongs to trusted script state.

Worked example · Request graceful termination

kill -TERM "$pid"

kill sends a termination request. A program with a SIGTERM handler can perform orderly cleanup; without one, the default action terminates it without guaranteeing user-space cleanup.

Useful contrast · Uncatchable termination

kill -KILL "$pid"

SIGKILL cannot be caught, blocked, or ignored, so process-level cleanup handlers and shell traps do not run.

Common mistakes

Misconceptions to remove early

Using SIGKILL as the first choice

SIGKILL prevents application cleanup and state flushing; request termination with SIGTERM first unless immediate forced termination is required.

Registering cleanup before resource creation succeeds

Validate and resolve the exact temporary resource first so cleanup never expands an empty, stale, or overly broad target.

Quick check

Can you predict the result?

1. Which of these signals cannot be caught or handled for cleanup?
  • SIGKILL
  • SIGTERM
  • SIGINT
Answer: SIGKILL
2. Why is SIGTERM usually preferred before SIGKILL?
Answer: It requests termination while allowing the target's normal signal handling and cleanup to run.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster