trap – Trap Signals and Other Events and Execute Commands

The trap command in Linux is used to trap signals and other events and execute commands when they occur. This command is commonly used to handle signals or errors that occur during the execution of a script or program.

Overview

The trap command allows you to specify commands that will be executed when specific signals or events occur. The syntax of the trap command is as follows:

trap COMMAND SIGNALS
  • COMMAND: The command to be executed when the specified signal is received. This can be any valid Linux command or a shell function.
  • SIGNALS: The signal(s) to be trapped. This can be a signal number (e.g. 1 for SIGHUP) or a signal name (e.g. HUP for SIGHUP). Multiple signals can be specified by separating them with spaces.

Here is an example of using the trap command to handle the SIGINT signal (generated by pressing Ctrl+C):

#!/bin/bash

function cleanup {
    echo "Cleaning up..."
    rm -f /tmp/myfile
    exit 1
}

trap cleanup SIGINT

echo "Press Ctrl+C to interrupt..."
while true; do
    sleep 1
done

In this example, the cleanup function is defined to remove a temporary file and exit the script. The trap command is used to execute the cleanup function when the SIGINT signal is received. The script then enters an infinite loop, waiting for the signal to be received.

Options

The following table lists the available options for the trap command:

Option Description
-l List all signal names and their corresponding numbers.
-p Display the current trap commands for each specified signal.
-s Specify the signal to be trapped by name instead of number.

Troubleshooting Tips

  • If you are having trouble trapping a signal, make sure that the signal is being sent to the correct process. You can use the kill command to send a signal to a specific process by PID.
  • If you are using the trap command in a script that is being sourced (e.g. source myscript.sh), the trap commands will be inherited by the calling shell. To avoid this, use the trap command inside a function instead of at the top level of the script.

Notes

  • The trap command can also be used to execute commands when a script exits, either normally or due to an error. To do this, use the EXIT signal.
  • The trap command is not limited to handling signals. It can also be used to execute commands when other events occur, such as when a variable is unset (trap 'echo "Variable unset"' UNSET).
  • The trap command is a powerful tool for handling errors and other unexpected events in your scripts and programs. With a little creativity, it can be used to handle a wide variety of situations.