Trap Command

Overview

The trap command catches signals and interruptions in your script to handle unexpected events gracefully.

Syntax: trap <arg/function> <signal>

Code

Basic Example

#!/bin/bash
 
# trap Ctrl+C (SIGINT) and SIGTERM
trap "echo Booh!" SIGINT SIGTERM
 
echo "it's going to run until you hit Ctrl+Z"
echo "hit Ctrl+C to be blown away!"
 
while true; do
    sleep 60
done

Using a Function

#!/bin/bash
 
cleanup() {
  echo "Cleaning up..."
  rm -f /tmp/mytempfile
  exit 0
}
 
trap cleanup SIGINT SIGTERM
 
# main script logic
while true; do
    sleep 60
done

Common Use Cases

# cleanup temporary files on exit
trap "rm -f /tmp/tempfile; exit" 2 15
 
# cleanup on any exit (including normal)
trap "rm -rf $TMPDIR" EXIT
 
# ignore a signal
trap "" SIGINT
 
# reset trap to default behavior
trap - SIGINT

Details

Common Signals

NumberSignalDescription
2SIGINTUser sends interrupt (Ctrl+C)
3SIGQUITUser sends quit (Ctrl+D)
8SIGFPEAttempted illegal mathematical operation
9SIGKILLKill (cannot be trapped)
15SIGTERMTermination signal

List all available signals:

kill -l

You can use signal numbers instead of names:

# 2 = SIGINT, 15 = SIGTERM
trap cleanup 2 15

Appendix

Note created on 2025-12-23 and last modified on 2025-12-23.

See Also


(c) No Clocks, LLC | 2025