2014-07-07 34 views
3

運行以下腳本
按Ctrl + C
觀察當前終端行爲。
按下輸入次數並嘗試執行一些命令。從使用讀取和陷阱的bash腳本中清除退出

#!/bin/bash 
LOCK_FILE=/tmp/lockfile 
clean_up(){ 
    # Perform program exit housekeeping 
    echo -e "Signal Trapped, exiting..." 
    # Do some Special operation 
    rm -f $LOCK_FILE 
    # 
    exit 1 
} 

touch LOCK_FILE 
trap clean_up SIGHUP SIGINT SIGTERM 
read -s -p "Password: " var 
echo -e "\n Input Password is: $var\n" 

我想知道我在做什麼錯誤?
我嘗試做一個乾淨的退出。 它正在工作,但出口終端STDIN消失後。

+0

你還沒有說你期望它做什麼或它在你的機器上做了什麼。 – l0b0

+0

@ l0b0實際上,我測試過了,它很奇怪。在捕獲SIGINT時,它會退出程序並弄亂你的shell(當你編寫一個命令時沒有字符出現,當你按下回車鍵時沒有新行)。當您鍵入重置時,這是固定的。儘管 – Aserre

+0

適合我,但我不知道他的劇本爲何如此。 – l0b0

回答

3

read -s如果你在ctrl-c之外,禁用本地回聲(根據文檔),它將無法重置本地回聲的終端模式。比較中斷讀取前後stty -a的輸出以查看所做更改(查看echo*模式)。

您可以使用reset(按照Plutox的評論)或手動重新啓用本地回聲模式來「解決」問題。

$ stty -a 
speed 38400 baud; rows 46; columns 80; line = 0; 
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; 
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; 
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; 
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr 
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff 
-iuclc -ixany imaxbel -iutf8 
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt 
echoctl echoke 
$ 
$ cat t.sh 
#!/bin/bash 
clean_up(){ 
    # Perform program exit housekeeping 
    echo -e "Signal Trapped, exiting..." 
    # Do some Special operation 
    rm -f $LOCK_FILE 
    # 
    exit 1 
} 

trap clean_up SIGHUP SIGINT SIGTERM 
read -s -p "Password: " var 
echo -e "\n Input Password is: $var\n" 
$ 
$ sh t.sh 
Password: Signal Trapped, exiting... 
# I ran `stty -a` here but the lack of local echo means it didn't show up. 
$ speed 38400 baud; rows 46; columns 80; line = 0; 
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; 
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; 
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; 
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr 
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff 
-iuclc -ixany imaxbel -iutf8 
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 
isig icanon iexten -echo echoe -echok -echonl -noflsh -xcase -tostop -echoprt 
echoctl echoke 
+0

+1。我正準備自己寫一個答案:),如果你不想顯示'stty -a'的(真的)詳細的輸出,只需在'exit1'之前加上'stty -a>/dev/null' 'clean_up()'函數 – Aserre

+1

@Ploutox'stty -a'不會改變它剛纔顯示的設置。添加到'clean_up'函數將無法解決問題。增加一個'重置'將會產生其他副作用。用'stty echo echok'手動重新啓用'echo'和'echok'設置可以解決這個問題。 –

+0

你試過了嗎?對於我在函數內使用它的效果很好 – Aserre