Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps