0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use trap in Bash: Syntax, Examples, and Tips

In Bash, use the trap command to specify commands that run when the script receives signals like EXIT or INT. This helps clean up or handle interruptions gracefully by trapping signals and executing your code.
📐

Syntax

The basic syntax of trap is:

  • trap <commands> <signals>

Here, <commands> is the code to run when a signal is caught, and <signals> are the signal names or numbers to catch.

Common signals include EXIT (script ends), INT (Ctrl+C), and TERM (termination request).

bash
trap 'echo "Signal caught! Cleaning up..."' EXIT
💻

Example

This example shows how to use trap to catch Ctrl+C (interrupt) and script exit to print messages and clean up.

bash
#!/bin/bash

trap 'echo "Interrupt signal received. Exiting..."; exit' INT
trap 'echo "Script finished."' EXIT

echo "Script started. Press Ctrl+C to interrupt."
sleep 10

echo "Script completed normally."
Output
Script started. Press Ctrl+C to interrupt. Script finished. Script completed normally.
⚠️

Common Pitfalls

Common mistakes when using trap include:

  • Not quoting commands properly, causing syntax errors.
  • Forgetting to handle signals like EXIT for cleanup.
  • Using commands that exit the script inside the trap without care, which can cause unexpected behavior.

Always test traps carefully to ensure they behave as expected.

bash
# Wrong way (missing quotes, will cause error)
trap echo "Caught signal" EXIT

# Right way
trap 'echo "Caught signal"' EXIT
📊

Quick Reference

SignalDescription
EXITRuns when the script exits for any reason
INTInterrupt signal (Ctrl+C)
TERMTermination signal
HUPHangup signal, often when terminal closes
ERRRuns on command errors if set -e is used

Key Takeaways

Use trap to run commands on signals like EXIT or INT for cleanup.
Always quote the commands in trap to avoid syntax errors.
Test traps to ensure they behave correctly on script exit or interruption.
Common signals to trap include EXIT, INT (Ctrl+C), and TERM.
Trap helps make scripts more robust and user-friendly by handling unexpected stops.