How to read just a single character in shell script
In ksh you can basically do:
stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
read -n1
works for bash
The stty raw
mode prevents ctrl-c from working and can get you stuck in an input loop with no way out. Also the man page says stty -raw
is not guaranteed to return your terminal to the same state.
So, building on dtmilano's answer using stty -icanon -echo
avoids those issues.
#/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"
In bash, read
can do it:
read -n1 ans