Skip to content

Instantly share code, notes, and snippets.

@markusfisch
Last active January 15, 2016 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusfisch/840c75c796f0a39f6b75 to your computer and use it in GitHub Desktop.
Save markusfisch/840c75c796f0a39f6b75 to your computer and use it in GitHub Desktop.
Read a key from stdin in bash
#!/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