捕捉键盘中断

j.l*_*lee 8 bash scripting

我有一个bash脚本,它在循环中执行程序并从程序中读取输出.我希望当我点击control-c时,它会终止程序以及脚本.

我试过这个,但似乎没有终止程序.

control_c() {
   exit
}

while true ; do 

    trap control_c SIGINT

    my_command | while read line ; do
       echo $line 
       ...
    done
done
Run Code Online (Sandbox Code Playgroud)

有人能告诉我完成我所描述的正确方法吗?谢谢!

aln*_*net 7

你可以这样做:

control_c() {
    kill $PID
    exit
}

trap control_c SIGINT

while true ; do 
   my_command | while read line ; do
   PID=$!
   echo $line 
   ...
done
Run Code Online (Sandbox Code Playgroud)


Rus*_*vis 4

尝试终止函数中的程序control_c(),例如,

pkill my_command
Run Code Online (Sandbox Code Playgroud)