Script Valley
Bash Scripting for Developers
Process Management and AutomationLesson 5.2

Bash signals and trap for graceful shutdown

Unix signals, SIGTERM SIGINT SIGKILL SIGHUP, trap syntax, trap with signal names, cleanup on exit, forwarding signals to child processes, kill command, signal numbers

Signals: OS Messages to Processes

Signal trap and cleanup flow

Signals are asynchronous notifications from the OS or other processes. Scripts need to handle them to clean up resources and shut down gracefully.

# Key signals
# SIGINT  (2)  โ€” Ctrl+C
# SIGTERM (15) โ€” default kill signal
# SIGHUP  (1)  โ€” terminal closed / reload config
# SIGKILL (9)  โ€” unblockable, instant termination

#!/usr/bin/env bash
tmpdir=$(mktemp -d)
child_pids=()

cleanup() {
  echo "Caught signal, shutting down..."
  # Kill all child processes
  for pid in "${child_pids[@]:-}"; do
    kill "$pid" 2>/dev/null
  done
  rm -rf "$tmpdir"
  echo "Cleanup complete"
  exit 0
}

trap cleanup INT TERM

# Simulate work with children
for i in 1 2 3; do
  sleep 100 &
  child_pids+=("$!")
done

wait  # blocks until signal or children finish

Reload Config on SIGHUP

load_config() {
  source /etc/myapp/config.sh
}

trap load_config HUP
load_config

while true; do
  do_work
done

SIGKILL (9) cannot be trapped โ€” the OS kills the process immediately. Never rely on cleanup happening after kill -9. Always try SIGTERM first and give the process time to clean up.

Up next

Scheduling Bash scripts with cron and systemd timers

Sign in to track progress

Bash signals and trap for graceful shutdown โ€” Process Management and Automation โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley