Shell Scripting / Bash Tricks
Stop wrestling with complex process signals in your scripts
đź§© The Challenge
You’ve got a script running a background job, but when you send a SIGINT or SIGTERM to the parent, the child processes keep running like zombies, clogging up your server. I’ve spent way too many mornings cleaning up orphaned processes because I forgot to trap signals properly.
đź’ˇ The Fix
Use a trap command to explicitly send the kill signal to the process group when your main script exits. It’s the only way to make sure you aren’t leaving stray subprocesses behind to rot.
trap 'kill $(jobs -p)' EXIT
some_long_running_command &
wait $!
⚙️ Why It Works
Setting a trap on the EXIT signal tells the shell to execute your cleanup command whenever the script terminates, whether it finishes naturally or gets zapped by a signal. By using $(jobs -p), you’re grabbing the PIDs of all background jobs started in the current session so they get taken down with the ship.
🚀 Pro-Tip: Add a SIGTERM to that trap if you want to handle unexpected kills even more aggressively.
Linux Tips & Tricks | © ngelinux.com | 11/7/2026
