bash 捕捉键盘中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5810232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
catching keyboard interrupt
提问by j.lee
I have a bash script that is executing a program in a loop and reading the output from the program. I wish that when I hit control-c, it terminates the program as well as the script.
我有一个 bash 脚本,它在循环中执行程序并读取程序的输出。我希望当我点击 control-c 时,它会终止程序和脚本。
I tried this but does not seem to terminate the program.
我试过了,但似乎没有终止程序。
control_c() {
exit
}
while true ; do
trap control_c SIGINT
my_command | while read line ; do
echo $line
...
done
done
Can someone show me the correct way to accomplish what I have described? Thank you!
有人可以告诉我完成我所描述的事情的正确方法吗?谢谢!
回答by alnet
You can do something like this:
你可以这样做:
control_c() {
kill $PID
exit
}
trap control_c SIGINT
while true ; do
my_command | while read line ; do
PID=$!
echo $line
...
done
回答by Russell Davis
Try killing the program in your control_c()function, e.g.,
尝试杀死您control_c()函数中的程序,例如,
pkill my_command

