jobs
trap
Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.
trap [ACTION] SIGNAL ... Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| EXIT | Run ACTION when the shell/script exits (any reason) |
| ERR | Run when a command returns non-zero (pairs with set -e) |
| INT / TERM | Ctrl-C interrupt / termination signal |
| -l | List signal names and numbers |
| -p | Print current traps in reusable form |
| trap - SIG | Reset SIG to default handling |
Examples
trap 'rm -f "$tmp"' EXIT Guarantee tempfile cleanup regardless of exit path.
trap 'echo failed on line $LINENO' ERR Diagnostic line-number reporting; pair with set -eE.
trap '' INT Ignore Ctrl-C for the rest of the script.
trap - INT Restore default Ctrl-C behavior.
Gotcha
Traps do NOT inherit into functions or subshells by default — use 'set -E' so ERR traps inherit. Single-quote the ACTION so variables like $LINENO expand at trap-time, not registration-time.
Related
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.
exec
Replaces the current shell process with COMMAND (no new process is created). Without a command, applies redirections permanently to the current shell — a common way to open long-lived file descriptors.
wait
Blocks until specified background jobs or PIDs complete, returning the exit status of the last one waited for. Essential for scripts that launch parallel background work and need to synchronize.
jobs / bg / fg
Interactive job control: jobs lists background/stopped jobs, bg resumes a stopped job in the background, fg brings it to the foreground. Jobs are addressed with %N, %+, %-, or %string.