shell 移除信号捕获
本例中用到的trap命令会在每次检测到SIGINT信号时显示一行简单的文本消息。捕获这些信号会阻止用户用bash shell组合键Ctrl+C来停止程序
code
macname@MacdeMacBook-Pro Desktop % cat test.sh #!/bin/bash # Testing signal trapping # trap "echo ' Sorry! I have trapped Ctrl-C'" SIGINT echo This is a test script count=1 while [ $count -le 10 ] do echo "Loop #$count" sleep 1 count=$[ $count + 1 ] done # echo "This is the end of the test script" #% macname@MacdeMacBook-Pro Desktop % macname@MacdeMacBook-Pro Desktop % ./test.sh This is a test script Loop #1 Loop #2 ^C Sorry! I have trapped Ctrl-C Loop #3 Loop #4 Loop #5 ^C Sorry! I have trapped Ctrl-C Loop #6 Loop #7 ^C Sorry! I have trapped Ctrl-C Loop #8 Loop #9 Loop #10 This is the end of the test script macname@MacdeMacBook-Pro Desktop %
移除信号捕获后,脚本按照默认行为来处理SIGINT信号,也就是终止脚本运行。但如果信 号是在捕获被移除前接收到的,那么脚本会按照原先trap命令中的设置进行处理。
macname@MacdeMacBook-Pro Desktop % ./test.sh Loop #1 Loop #2 Loop #3 ^C Sorry... Ctrl-C is trapped. Loop #4 Loop #5 I just removed the trap Second Loop #1 Second Loop #2 Second Loop #3 ^C macname@MacdeMacBook-Pro Desktop % cat test.sh #!/bin/bash # Removing a set trap trap "echo ' Sorry... Ctrl-C is trapped.'" SIGINT count=1 while [ $count -le 5 ] do echo "Loop #$count" sleep 1 count=$[ $count + 1 ] done # # Remove the trap trap -- SIGINT echo "I just removed the trap" count=1 while [ $count -le 5 ] do echo "Second Loop #$count" sleep 1 count=$[ $count + 1 ] done macname@MacdeMacBook-Pro Desktop %
当脚本运行到正常的退出位置时,捕获就被触发了,shell会执行在trap命令行指定的命令。 如果提前退出脚本,同样能够捕获到EXIT。
macname@MacdeMacBook-Pro Desktop % ./test.sh Loop #1 Loop #2 Loop #3 Loop #4 Loop #5 Goodbye... macname@MacdeMacBook-Pro Desktop % ./test.sh Loop #1 Loop #2 ^CGoodbye... macname@MacdeMacBook-Pro Desktop % cat test.sh #!/bin/bash # Trapping the script exit # trap "echo Goodbye..." EXIT # count=1 while [ $count -le 5 ] do echo "Loop #$count" sleep 1 count=$[ $count + 1 ] done% macname@MacdeMacBook-Pro Desktop %