Bash trap (Signals)
A signal is a message sent to a running process, such as INT (Ctrl+C) or TERM (the default signal of kill).
trap runs your own commands when a signal arrives, or on EXIT when the script ends. It is often used to clean up temporary files.
Clean up on exit
Save this as cleanup.sh:
#!/bin/bash
trap 'echo "Cleaning up"; rm -f temp.txt' EXIT
echo "data" > temp.txt
echo "Working..."
Run it:
./cleanup.sh
Working...
Cleaning up
Catch a signal
The script sends TERM to itself with kill, and the trap catches it. Save this as signal.sh:
#!/bin/bash
trap 'echo "Got TERM, stopping"; exit 1' TERM
echo "Running"
kill -TERM $$
echo "Never printed"
Run it:
./signal.sh
Running
Got TERM, stopping