Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
Signal Trapping (`trap`) for graceful cleanup of temporary files on `EXIT`, `INT`, and `TERM`.
senior LevelCode ExampleSignals
In Simple Words:
Scripts frequently create temporary files in /tmp. If a user presses Ctrl+C (SIGINT) or the process is killed (SIGTERM), orphaned files clutter the disk.
The trap command registers guaranteed cleanup handlers:
bash
#!/usr/bin/env bash
set -euo pipefail
TEMP_DIR=$(mktemp -d /tmp/myapp.XXXXXX)
# Guaranteed cleanup whether script exits normally or crashes!
cleanup() {
echo "Cleaning up temporary files..."
rm -rf "$TEMP_DIR"
}
trap cleanup EXIT INT TERM
echo "Working inside $TEMP_DIR"