清理临时文件
你可以使用trap命令来捕获信号;shell中的trap捕获信号等同于C语言或大多数其它语言中的signal或者sigaction。
trap最常用的场景之一是在预期退出和意外退出时清理临时文件。
遗憾的是没有多少shell脚本这样做。
- #!/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.
捕获SIGINT或Ctrl+C信号
当有子shell时,trap会被重置,所以sleep继续作用于由^C发送的SIGINT信号,而父进程(即shell脚本)就不会了。所以下面的例子只是退出了sleep,没有直接退出shell脚本,而是继续往下执行。
- #!/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
通过些许更改可以允许你按两个^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
统计维护退出任务
你有没有在退出时忘记添加trap来清理临时文件或者其它事情?
有没有设置了一个trap而导致取消了另一个?
下面的代码能让你非常容易地在一个地方就把所有需要在退出时做的工作都添加进去,而不是需要一大段的trap声明,这个很容易忘记的。
- # 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
- }
退出时杀掉子进程
Trap表达式不一定需要单独的函数或者程序,它也可以直接使用复杂的表达式,如:
- trap 'jobs -p | xargs kill' EXIT