虽然它可能会让许多人感到震惊,但您可以使用bash内置陷阱来捕获信号:-)
好吧,至少那些可以被捕获,但CTRL-C通常与INT信号相关联.您可以捕获信号并执行任意代码.
以下脚本将要求您输入一些文本,然后将其回显给您.如果偶然,你生成一个INT信号,它只会咆哮你并退出:
#!/bin/bash
exitfn () {
trap SIGINT # Restore signal handling for SIGINT
echo; echo 'Aarghh!!' # Growl at user,
exit # then exit script.
}
trap "exitfn" INT # Set up SIGINT trap to call function.
read -p "What? " # Ask user for input.
echo "You said: $REPLY"
trap SIGINT # Restore signal handling to previous before exit.
测试运行记录如下(完全输入的行,在任何条目之前按下CTRL-C的行,以及在按CTRL-C之前具有部分条目的行):
pax> ./testprog.sh
What? hello there
You said: hello there
pax> ./testprog.sh
What? ^C
Aarghh!!
pax> ./qq.sh
What? incomplete line being entere... ^C
Aarghh!!