trap
Syntax
trap [COMMANDS] [SIGNALS ...]
When Bash receives a signal for which a trap has been set while waiting for a command to complete,
the trap will not be executed until the command completes.
Signals can be sent to your programs using the kill command or keyboard shortcuts(ie. Ctrl+C).
When Bash is waiting for an asynchronous command via the wait built-in,
the reception of a signal for which a trap has been set will cause the wait built-in to return immediately with an exit status greater than 128
* The return status of the trap command itself is zero unless an invalid signal specification is encountered.
SIGNALS
- EXIT # 所有的 exit. ie. exit 0 | exit 1 ...
- SIGHUP # 1, Hangup
- SIGINT # 2, Ctrl+C
- SIGTERM # 15
- SIGKILL # 9. Can not be caught
- SIGTSTP # Ctrl+Z
- DEBUG
- SIGUSR1 # "user"-defined signal => you can use however you like
Example
1) Run Script when press "Ctrl+C"
#!/bin/bash
function cleanup(){
echo 'Press "Ctrl+C"'
}
trap cleanup SIGINT
ping 8.8.8.8
# OUTPUT 'Press "Ctrl+C"'
ping 8.8.4.4
2) script exit
#!/bin/bash [email protected] function mail2admin(){ echo "Exit Code: $?" echo "Send mail to: $ADMIN" } trap mail2admin EXIT exit 1