How to use trap for signal handling in bash

· Category: Linux

Short answer

trap catches signals like INT, TERM, and EXIT to run cleanup code before a script terminates.

Steps

  1. Trap Ctrl+C:
trap "echo 'Interrupted'; exit 1" INT
  1. Cleanup on exit:
trap "rm -f /tmp/tempfile" EXIT
  1. Ignore a signal:
trap "" HUP
  1. Reset to default:
trap - INT

Tips

  • Always clean up temporary files and locks with trap.
  • ERR trap runs on any command failure when set -E is enabled.
  • Define cleanup functions for complex scripts.

Common issues

  • kill -9 (SIGKILL) cannot be trapped.
  • Nested traps may overwrite each other; save and restore with variables.