2011-04-27 66 views
6

我有一個bash腳本,它執行循環中的程序並讀取程序的輸出。我希望當我擊中control-c時,它會終止程序以及腳本。捕獲鍵盤中斷

我試過這個,但似乎並沒有終止程序。

control_c() { 
    exit 
} 

while true ; do 

    trap control_c SIGINT 

    my_command | while read line ; do 
     echo $line 
     ... 
    done 
done 

有人能告訴我正確的方法來完成我所描述的嗎?謝謝!

回答

2

嘗試在你的control_c()功能查殺程序,例如,

pkill my_command 
4

你可以做這樣的事情:

control_c() { 
    kill $PID 
    exit 
} 

trap control_c SIGINT 

while true ; do 
    my_command | while read line ; do 
    PID=$! 
    echo $line 
    ... 
done