Tags: #shell
#!/usr/bin/env bash
cleanup() {
echo ">>> cleanup called (reason: $1)"
}
# Trap EXIT, INT, TERM
# In the following code we're passing the 'signal' as an argument to the cleanup function.
#
# trap 'cleanup EXIT' EXIT
# trap 'cleanup INT' INT
# trap 'cleanup TERM' TERM
# INT/TERM would normally stop the script immediately.
# But when you trap them, you replace the default action with whatever you tell the shell to do.
# You need to explicitly tell the shell to exit after cleanup, e.g.:
trap 'cleanup INT; exit 130' INT # 130 is the conventional exit code for SIGINT
trap 'cleanup TERM; exit 143' TERM # 143 = 128 + 15 (SIGTERM)
trap 'cleanup EXIT' EXIT
echo "PID $$ running. Try:"
echo " 1) Let it finish normally"
echo " 2) Press Ctrl+C"
echo " 3) Run: kill -TERM $$"
echo
# Simulate doing some work
for i in {1..10}; do
echo "Working... $i"
sleep 1
done
echo "Script finished normally."