Bash Using "trap" to react to signals and system events Introduction: clean up temporary files


You can use the trap command to "trap" signals; this is the shell equivalent of the signal() or sigaction() call in C and most other programming languages to catch signals.

One of the most common uses of trap is to clean up temporary files on both an expected and unexpected exit.

Unfortunately not enough shell scripts do this :-(


# Make a cleanup function
cleanup() {
  rm --force -- "${tmp}"

# Trap the special "EXIT" group, which is always run when the shell exits.
trap cleanup EXIT

# Create a temporary file
tmp="$(mktemp -p /tmp tmpfileXXXXXXX)"

echo "Hello, world!" >> "${tmp}"

# No rm -f "$tmp" needed. The advantage of using EXIT is that it still works
# even if there was an error or if you used exit.