Trap command
tarp
The command is used to perform the action after the specified signal is received, usually in order to complete the cleanup when the shell script is interrupted. For example:
When the script is pressed at execution time CTRL+c
, "program exit ..." is displayed and exits ( CTRL+c
the signal is SIGINT)
#!/bin/bashtrap "ehco ‘program exit...‘; exit 2" SIGINT....
Signal
Common signals
signal name |
signal number |
|
sigint |
2 |
|
sigquit |
3 |
|
sigfpe |
8 |
In the event of fatal arithmetic Is emitted when an operation is wrong. This includes not only floating-point arithmetic errors, but also all other arithmetic errors such as overflow and divisor 0. |
sigkill |
9 |
|
sigalrm |
14 |
clock timing signal , the actual time or clock time is calculated. The alarm function uses this signal. SIGTERM |
Capture Signal
Command syntax for trap:
shell trap command signal
This command
can be a Linux command, or a user-defined function. signal
is the signal name or number of signals, you can specify multiple signals, separated by a space.
trap
Common use in the shell
- Execute command before script exits
When the script is pressed at execution time CTRL+c
, "program exit ..." is displayed and exits ( CTRL+c
the signal is SIGINT)
trap "ehco ‘program exit...‘; exit 2" SIGINT
Example: Ignoring SIGINT
SIGQUIT
SIGFPE
such signals while the script is running
trap ‘‘ 2 3 8
Shell Signal capture Command trap