Web Analytics

Signal Handling

Advanced~25 min read

Use trap to intercept signals and perform cleanup, ensuring your script exits predictably.

trap Basics

Output
Click Run to execute your code
Note: Always handle EXIT for final cleanup, even on successful runs.
Pro Tip: Group cleanup logic in a function and call it from all traps to avoid duplication.
Caution: Some signals cannot be trapped (e.g., SIGKILL, SIGSTOP).

Common Mistakes

1) Forgetting to quote trap commands

Write trap 'cleanup' INT instead of unquoted forms that can break on spaces.

2) Not removing temporary artifacts

Ensure temporary files and child processes are cleaned on all exit paths.

Exercise: Graceful Cancel

Task: Set up a trap for SIGINT that prints a message and exits with code 130.

Output
Click Run to execute your code
Show Solution
trap 'echo "Canceled"; exit 130' INT

Summary

  • Use trap for cleanup on signals and exit.
  • Centralize cleanup in a function.
  • Know which signals are non-trappable.

What's Next?

Run concurrent tasks and manage job control in Background Jobs.