2012-01-04 45 views

回答

5

KSH中,你基本上可以做到:

stty raw 
REPLY=$(dd bs=1 count=1 2> /dev/null) 
stty -raw 
12

在bash,read可以做到這一點:

read -n1 ans 
+0

給出'0403-010指定的標誌對此命令無效.'錯誤。 – footy 2012-01-04 12:23:36

+0

@footy,bash的內置讀命令有-n選項。你在用什麼外殼? – 2012-01-04 12:46:08

+0

@glennjackman ksh shell我正在使用 – footy 2012-01-04 12:52:34

7

read -n1作品慶典

stty raw模式防止CTRL-C從工作並可以讓你陷入一個沒有出路的輸入循環。此外,手冊頁上說stty -raw不保證將您的終端返回到相同的狀態。

因此,建立在dtmilano's answer上使用stty -icanon -echo可以避免這些問題。

#/bin/ksh 
## /bin/{ksh,sh,zsh,...} 

# read_char var 
read_char() { 
    stty -icanon -echo 
    eval "$1=\$(dd bs=1 count=1 2>/dev/null)" 
    stty icanon echo 
} 

read_char char 
echo "got $char"