Clear temporary files
You can use the trap command to capture signals. The trap capture signals in shell are equivalent to signal or sigaction in C language or most other languages.
One of the most common scenarios of trap is to clear temporary files when expected and unexpected exits.
Unfortunately, there are not many shell scripts.
#! /Bin/sh
# Make a cleanup function
Cleanup (){
Rm -- force -- "$ {tmp }"
}
# Trap the special "EXIT" group, which is always run when the shell exits.
Trap cleanup EXIT
# Create a temporary file
Tmp = "$ (mktemp-p/tmp tmpfileXXXXXXX )"
Echo "Hello, world! ">>" $ {Tmp }"
# No rm-f "$ tmp" needed. The advantage of using EXIT is that it still works
# Even if there was an error or if you used exit.
Capture SIGINT or Ctrl + C signals
When there is a sub-shell, the trap will be reset, so sleep continues to act on the SIGINT signal sent by ^ C, and the parent process (that is, shell script) won't. Therefore, the following example only exits sleep, instead of directly exiting the shell script, but continues to run.
#! /Bin/sh
# Run a command on signal 2 (SIGINT, which is what ^ C sends)
Sigint (){
Echo "Killed subshell! "
}
Trap sigint INT
# Or use the no-op command for no output
# Trap: INT
# This will be killed on the first ^ C
Echo "Sleeping ..."
Sleep 500
Echo "Sleeping ..."
Sleep 500
With some changes, you can exit the program by pressing two ^ C:
Last = 0
Allow_quit (){
[$ (Date + % s)-lt $ ($ last + 1)] & exit
Echo "Press ^ C twice in a row to quit"
Last = $ (date + % s)
}
Trap allow_quit INT
Statistical maintenance exit task
Did you forget to add the trap when you exit to clear the temporary files or other things?
Has one trap been set and the other is canceled?
The following code makes it easy to add all the work that needs to be done at exit in one place, rather than a large segment of trap Declaration. This is easy to forget.
# On_exit and add_on_exit
# Usage:
# Add_on_exit rm-f/tmp/foo
# Add_on_exit echo "I am exiting"
# Tempfile = $ (mktemp)
# Add_on_exit rm-f "$ tempfile"
# Based on http://www.linuxjournal.com/content/use-bash-trap-statement-cleanup-temporary-files
Function on_exit ()
{
For I in "$ {on_exit_items [@]}"
Do
Eval $ I
Done
}
Function add_on_exit ()
{
Local n =$ {# on_exit_items [*]}
On_exit_items [$ n] = "$ *"
If [[$ n-eq 0]; then
Trap on_exit EXIT
Fi
}
Kill sub-process upon exit
Trap expressions do not necessarily need independent functions or programs. They can also directly use complex expressions, such:
Trap 'jobs-p | xargs kill' EXIT