How to read just a single character in shell script
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 varread_char() { stty -icanon -echo eval "$1=\$(dd bs=1 count=1 2>/dev/null)" stty icanon echo}read_char charecho "got $char"