What are common `trap` command use cases?

QuestionsQuestions8 SkillsProBash Trap CommandNov, 29 2025
073

Common use cases for the trap command in Bash include:

  1. Cleanup on Exit: Automatically remove temporary files or release resources when a script exits or is interrupted.

    trap 'rm -f /tmp/tempfile; exit' EXIT
  2. Graceful Handling of Interrupts: Allow scripts to handle user interruptions (like Ctrl+C) gracefully, providing a message or performing cleanup.

    trap 'echo "Script interrupted"; exit' SIGINT
  3. Logging Events: Log messages or actions when specific signals are received, useful for debugging or monitoring.

    trap 'echo "Received SIGHUP";' SIGHUP
  4. Preventing Data Loss: Ensure that critical operations are completed or saved before a script is terminated.

    trap 'save_data; exit' SIGTERM
  5. Custom Signal Handling: Define custom behavior for user-defined signals (SIGUSR1, SIGUSR2) to control script execution.

    trap 'echo "Custom signal received";' SIGUSR1
  6. Timeouts: Use trap with SIGALRM to handle timeouts in scripts.

    trap 'echo "Timeout occurred"; exit' SIGALRM

These use cases help improve the robustness and reliability of Bash scripts by managing unexpected events and ensuring proper resource management.

0 Comments

no data
Be the first to share your comment!