trap - Linux
Overview
The trap
command in Linux is used to specify and handle signals and other system events during the execution of a shell script or a command. It defines actions to take when the script receives signals like INT (interrupt) or TERM (terminate). Utilizing trap
can enhance script robustness by gracefully handling unexpected events or cleanup tasks.
Syntax
The basic syntax of the trap
command is:
trap [OPTIONS] [ARG] [SIGNUM...]
Where ARG
is the command to execute when one of the SIGNUM
signals is received. SIGNUM
can be a signal number or name (like SIGINT
or 2
). Multiple signals can be trapped by the same command by listing them with spaces.
Variations
- To remove a trap, use an empty string as the argument:
trap "" SIGNAL
- To reset the action for a signal to its default, use
-
as the argument:trap - SIGNAL
- To print the current trap settings, use:
trap -p
Options/Flags
-p
: Display the trap commands associated with each signal.-l
: List signal names and their corresponding numbers.
These options help inspect current traps and understand signal specifications.
Examples
- Basic trapping of a signal: Trap the SIGINT signal, usually triggered by pressing Ctrl+C:
trap "echo 'SIGINT received'" SIGINT
- Trap multiple signals: Perform cleanup operations for both SIGINT and SIGTERM:
trap "echo 'Cleanup operations'; exit" SIGINT SIGTERM
- Disable a trap: Disable the trap for a SIGINT:
trap - SIGINT
- Trap on script exit: Execute a command when the script exits normally or is interrupted:
trap "echo 'Script is terminating'" EXIT
Common Issues
- Trap not triggering: Ensure the script is running in a context where it can receive signals. Some subshells or script modes may not handle traps as expected.
- Using variables in traps: Variables used in traps are evaluated when the trap is declared, not when triggered. Use single quotes to delay evaluation.
Integration
Combine trap
with other commands for robust script management:
- Creating a temporary file and ensuring its deletion:
temp_file=$(mktemp) trap "rm -f $temp_file" EXIT # Use temporary file in script
- Integrating with
sleep
for interruptible waits:trap "exit" INT echo "Waiting for 5 seconds. Press Ctrl+C to interrupt." sleep 5
Related Commands
kill
: Send signals to other processes.ps
: Monitor or control active processes, useful for identifying process IDs to send signals withkill
.
For further reading, consider the official GNU Bash documentation or use man trap
on most Linux systems for more details.