How to use the command 'trap' (with examples)
The command ’trap’ allows users to set up actions that are automatically executed when a process or the operating system receives a signal. It can be used to perform cleanups or other actions in response to interruptions. This article will illustrate several use cases of this command.
Use case 1: List available signals to set traps for
Code:
trap -l
Motivation: When setting up traps, it is important to know the available signals that can be used. This command allows us to list the available signals for reference.
Explanation: The ‘-l’ option is used to list the available signals that can be used to set traps.
Example output:
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM ...
Use case 2: List active traps for the current shell
Code:
trap -p
Motivation: Sometimes, it is necessary to check the currently active traps in the current shell. This command allows us to do that.
Explanation: The ‘-p’ option is used to print the active traps for the current shell.
Example output:
trap -- 'echo "Caught signal SIGHUP"' SIGHUP
Use case 3: Set a trap to execute commands when one or more signals are detected
Code:
trap 'echo "Caught signal SIGHUP"' SIGHUP
Motivation: Setting traps can be useful in scenarios where we want to perform specific actions in response to signals. In this example, we set a trap to echo a message when the SIGHUP signal is detected.
Explanation:
The trap command is used to set a trap. Here, we specify the command to be executed (echo "Caught signal SIGHUP"
) when the specified signal (SIGHUP
) is detected.
Example output:
(no output unless the SIGHUP signal is sent)
Use case 4: Remove active traps
Code:
trap - SIGHUP SIGINT
Motivation: Sometimes, we may want to remove the active traps so that they no longer execute their associated commands.
Explanation:
The ‘-’ option is used to remove active traps. Here, we specify the signals (SIGHUP
and SIGINT
) for which we want to remove the traps.
Example output:
(no output unless there were active traps for the specified signals)
Conclusion:
The ’trap’ command is a powerful tool for automatically executing commands in response to signals. It can help with performing cleanups or other actions when interruptions occur. By understanding its various use cases, users can make better use of this command in their shell scripts or interactive sessions.