How do you handle SIGTERM gracefully in a long-running script?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
stop=0
trap 'stop=1' TERM INT
while (( ! stop )); do
process_next_batch
sleep 5 & wait $! # wait is interruptible by signals, sleep is not
done
echo "finished current batch, exiting cleanly"
Bash defers trap handling until the current foreground command finishes, so a plain sleep 300 delays shutdown by up to 300 seconds. Running sleep in the background and waiting on it lets the trap fire immediately. This matters for systemd's TimeoutStopSec and Kubernetes' terminationGracePeriodSeconds.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner