Last active
January 15, 2016 17:26
-
-
Save markusfisch/840c75c796f0a39f6b75 to your computer and use it in GitHub Desktop.
Read a key from stdin in bash
This file contains 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
#!/usr/bin/env bash | |
# Process literal key | |
process_literal_key() | |
{ | |
case "$REPLY" in | |
$'\E') | |
ESCAPE=1 | |
;; | |
'') | |
echo 'enter' | |
;; | |
$'\x7F') | |
echo 'back-space' | |
;; | |
q) | |
;; | |
*) | |
echo "DEBUG: [$REPLY]" | |
;; | |
esac | |
} | |
# Process control key | |
process_control_key() | |
{ | |
case $REPLY in | |
'[') | |
;; | |
*A) | |
echo 'up' | |
;; | |
*B) | |
echo 'down' | |
;; | |
*C) | |
echo 'left' | |
;; | |
*D) | |
echo 'right' | |
;; | |
*) | |
process_literal_key | |
;; | |
esac | |
ESCAPE= | |
} | |
# Read a key from stdin | |
read_keys() | |
{ | |
local ESCAPE= | |
while read -r -s -n 1 | |
do | |
if (( ESCAPE )) | |
then | |
process_control_key | |
else | |
process_literal_key | |
fi | |
done | |
} | |
if [ "${BASH_SOURCE[0]}" == "$0" ] | |
then | |
read_keys | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment