在Linux中,trap命令主要用于接收信号并采取行动,信号是异步发送到一个程序的事件,在默认情况下,可以终止一个程序,trap命令原型如下:
trap command signal
signal是指接收到的信号,command是接收到该信号采取的行动。如下为两种简单的信号。
信号
说明
INT(2)
Ctrl + C
QUIT(3)
Ctrl + \
示例代码如下
[root@localhost shell]# cat -n trap.sh
1 #!/bin/bash
2 trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
3 echo this is a test program
4 count=1
5 while [ $count -le 10 ]
6 do
7 echo "LOOP #$count"
8 sleep 5
9 count=$[ $count + 1]
10 done
11 echo this is the end of the test program
[root@localhost shell]#
运行时按下Ctrl+C结果如图:
[root@localhost shell]# ./trap.sh
this is a test program
LOOP #1
LOOP #2
^Csorry! I habe trapped Ctrl+C
LOOP #3
LOOP #4
^Csorry! I habe trapped Ctrl+C
LOOP #5
LOOP #6
LOOP #7
LOOP #8
^Csorry! I habe trapped Ctrl+C
LOOP #9
LOOP #10
this is the end of the test program
[root@localhost shell]#
如果想要捕捉shell脚本的退出,只要在trap命令上加EXIT信号就行,代码如下:
[root@localhost shell]# cat -n trap.sh
1 #!/bin/bash
2 trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
3 trap "echo goodbye" EXIT
4 echo this is a test program
5 count=1
6 while [ $count -le 10 ]
7 do
8 echo "LOOP #$count"
9 sleep 5
10 count=$[ $count + 1]
11 done
12 echo this is the end of the test program
[root@localhost shell]#
运行结果如下:
[root@localhost shell]# ./trap.sh
this is a test program
LOOP #1
^Csorry! I habe trapped Ctrl+C
LOOP #2
^Csorry! I habe trapped Ctrl+C
LOOP #3
^Csorry! I habe trapped Ctrl+C
LOOP #4
LOOP #5
LOOP #6
^Csorry! I habe trapped Ctrl+C
LOOP #7
^Csorry! I habe trapped Ctrl+C
LOOP #8
LOOP #9
LOOP #10
this is the end of the test program
goodbye
[root@localhost shell]#
还可以在shell中移除捕捉,代码如下:
[root@localhost shell]# cat -n trap.sh
1 #!/bin/bash
2 trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
3 trap "echo goodbye" EXIT
4 echo this is a test program
5 count=1
6 while [ $count -le 10 ]
7 do
8 echo "LOOP #$count"
9 sleep 1
10 count=$[ $count + 1]
11 done
12 echo this is the end of the test program
13 trap - EXIT
14 echo " I just remove EXIT trap "
在程序结束之前,移除了EXIT捕捉,最终就不会输出goodbye:
[root@localhost shell]# ./trap.sh
this is a test program
LOOP #1
LOOP #2
LOOP #3
LOOP #4
LOOP #5
LOOP #6
LOOP #7
LOOP #8
LOOP #9
LOOP #10
this is the end of the test program
I just remove EXIT trap
[root@localhost shell]#