Skip to content

Trap Command

The trap command in BASH allows scripts to execute specific actions when certain signals are received. This is essential for ensuring proper cleanup, such as removing temporary files or releasing resources, even if the script is interrupted. By leveraging trap, you can make your scripts more robust and reliable in unpredictable environments.

Basic Syntax and Signal Handling

The trap command takes two arguments: the command to execute and the signal to catch. Common signals include:

  • SIGINT (interrupt from keyboard, Ctrl+C)
  • SIGTERM (termination signal, default for kill)
  • SIGHUP (hangup, often used to terminate background processes)
  • EXIT (when the script exits normally)

Example:

trap 'echo "Caught SIGINT"' SIGINT

Performing Cleanup with Trap

A common use case is to clean up resources when a script is interrupted. For example, deleting a temporary file:

tempfile=$(mktemp)
echo "Temporary file created: $tempfile"

trap 'rm -f "$tempfile"; echo "Cleaned up temporary file"' EXIT

In this example, the temporary file is deleted when the script exits, regardless of how it terminates.

Handling EXIT and Ensuring Cleanup

The EXIT signal ensures cleanup occurs even if the script exits normally. Combining it with a function for cleanup:

cleanup() {
    rm -f "$tempfile"
    echo "Script exited cleanly."
}

trap 'cleanup' EXIT

Best Practices

  • Use Functions for Cleanup: Encapsulate cleanup logic in a function for reusability.
  • Avoid Redundant Traps: Only set traps for necessary signals to prevent conflicts.
  • Idempotent Cleanup: Ensure cleanup operations can be safely repeated without errors.
  • Note on Untrappable Signals: Signals like SIGKILL cannot be trapped, so rely on EXIT for predictable cleanup.

Key Takeaways

  • Use trap to execute cleanup code on signal reception.
  • Common signals include SIGINT, SIGTERM, and EXIT.
  • Always define cleanup functions to ensure resource release.
  • Avoid trapping signals that cannot be caught, like SIGKILL.
  • Combine trap EXIT with cleanup functions for guaranteed cleanup on script exit.