Created
September 10, 2025 09:00
-
-
Save Integralist/29024a8de49dcdf5ba9b24927e15cf05 to your computer and use it in GitHub Desktop.
Trapping Shell Signals #shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment