# Traps, Cleanup and Temporary Files — Bash / Shell Scripting

Source: https://www.skillbyai.com/en/bash/r-traps

> Clean up reliably on exit, error and interruption.

## Leave no mess behind

Scripts often create temporary files, lock files, mounted volumes or background processes that must be cleaned up even when something fails or the user presses Ctrl+C. The **`trap`** builtin runs a command when the shell receives a signal or reaches a special event. **`trap cleanup EXIT`** runs `cleanup` whenever the script exits, normally or because of an error under `set -e`, which covers most needs. You can also trap **`INT`** (Ctrl+C) and **`TERM`** (polite kill) to log and exit, and **`ERR`** to report the failing line, using `$LINENO` and `$BASH_COMMAND` (with `set -E` so the trap is inherited by functions). Create temporary files and directories with **`mktemp`**, which picks unique, unpredictable names in a safe location; never use fixed names like `/tmp/data.txt`, which collide between runs and can be abused by other users on shared machines.

## A cleanup trap and an error reporter

Temporary files disappear and failures report where they happened.

```bash
#!/usr/bin/env bash
set -Eeuo pipefail

workdir=$(mktemp -d)
cleanup() {
    local status=$?
    rm -rf "${workdir:?}"
    exit "$status"
}
trap cleanup EXIT
trap 'echo "error on line $LINENO: $BASH_COMMAND" >&2' ERR
trap 'echo "interrupted" >&2; exit 130' INT TERM

curl -fsSL "https://example.com/data.tar.gz" -o "$workdir/data.tar.gz"
tar -xzf "$workdir/data.tar.gz" -C "$workdir"
./import.sh "$workdir"/*.csv
# however the script ends, $workdir is removed
```

## Closing the shop at night

A trap on EXIT is the closing checklist pinned by the door: lights off, gas off, shutters down. It runs whether you close normally, rush out because of a problem, or are called away suddenly.

**Quiz:** Which trap is the most general way to ensure cleanup runs when a script ends?

- [ ] trap cleanup INT
- [x] trap cleanup EXIT
- [ ] trap cleanup HUP
- [ ] trap cleanup DEBUG

*Answer:* trap cleanup EXIT. The EXIT pseudo-signal fires whenever the shell exits, for any reason it can handle.
