2013-02-05 50 views

回答

7

雖然它可能會作爲一個衝擊很多,你可以使用bash內置trap捕獲信號:-)

嗯,至少是那些可以被捕獲,但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!! 
3

trap用於捕獲腳本中的信號,包括按下Ctrl-C時生成的SIGINT

+0

+1這樣好多了,我打算建議一個邏輯運算符來鏈接腳本。 – slezica