Last active
December 28, 2015 10:59
-
-
Save kurahaupo/7489751 to your computer and use it in GitHub Desktop.
How to read ANSI keyboard sequences in Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
The "return value" is in $key
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)