Skip to content

Instantly share code, notes, and snippets.

@kurahaupo
Last active December 28, 2015 10:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurahaupo/7489751 to your computer and use it in GitHub Desktop.
Save kurahaupo/7489751 to your computer and use it in GitHub Desktop.
How to read ANSI keyboard sequences in Bash
readkey() {
local char
IFS= \
read -rs -d '' -N1 key || return $? # use -n1 on older versions
while
case "$key" in
('') key=$'\n' ; break ;; # compensate for bug
( $'\e[M'??? ) break ;; # mouse report
( $'\e' | $'\e[' | $'\e['[?O] | $'\e['*[\;0-9] | $'\e[M'* | $'\eO' ) ;;
( [$'\xc0'-\$'xfe'] \
| [$'\xe0'-\$'xfe'][$'\x80'-$'\xbf'] \
| [$'\xf0'-\$'xfe']?[$'\x80'-$'\xbf'] \
| [$'\xf8'-\$'xfe']??[$'\x80'-$'\xbf'] \
| [$'\xfc'-\$'xfe']???[$'\x80'-$'\xbf'] \
| [$'\xfe'-\$'xfe']????[$'\x80'-$'\xbf'] ) ;; # don't stop on incomplete UTF-8 prefix
(*) break ;; # stop on anything else
esac
IFS= \
read -rs -d '' -N1 -t0.1 char # use -n1 -t1 on older versions
do
[[ -z "$char" ]] && char=' ' # compensate for bug
key="$key$char"
done
return 0
}
@kurahaupo
Copy link
Author

If using older versions of Bash, change the read parameters, from -N1 to -n1 and from -t0.1 to -t1 (Old versions don't support read-ignoring-delimiter or fractional seconds.)

@kurahaupo
Copy link
Author

The "return value" is in $key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment