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 forkill)SIGHUP(hangup, often used to terminate background processes)EXIT(when the script exits normally)
Example:
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:
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
SIGKILLcannot be trapped, so rely onEXITfor predictable cleanup.
Key Takeaways¶
- Use
trapto execute cleanup code on signal reception. - Common signals include
SIGINT,SIGTERM, andEXIT. - Always define cleanup functions to ensure resource release.
- Avoid trapping signals that cannot be caught, like
SIGKILL. - Combine
trap EXITwith cleanup functions for guaranteed cleanup on script exit.