This script reads a character from the keyboard using dd:
All common keys are detected properly, as well as the first byte of any escape sequence sent by a function key.
A small problem is the dd command. When the real escape key is pressed, dd keeps waiting on input of a possible sequence.
I need something like a timeout function to separate the input of a single escape and an escape sequence. Bash's read command has a -t option for it, and the C ncurses lib has the halfdelay/cbreak functions, but how is this possible in sh?
Code:
#!/bin/sh
stty -echo cbreak # turn off keyboard echoing and newline termination of all input
echo "tty is: $(tty). waiting on keyboard input..."
CHAR_1=$(dd if=$(tty) bs=1 count=1 2>/dev/null ) # read first byte
CHAR_1_VAL=$(printf "%d" "'$CHAR_1'")
if [ $CHAR_1_VAL != 27 ]
then
printf "standard key detected, value: $CHAR_1_VAL\n"
else
printf "escape detected, reading possible next byte...\n"
CHAR_2=$(dd if=$(tty) bs=1 count=1 2>/dev/null ) # keeps hanging on single escape
CHAR_2_VAL=$(printf "%d" "'$CHAR_2'") # and waits for another byte to read
printf "char 2 value was: $CHAR_2_VAL\n"
fi
stty echo -cbreak
All common keys are detected properly, as well as the first byte of any escape sequence sent by a function key.
A small problem is the dd command. When the real escape key is pressed, dd keeps waiting on input of a possible sequence.
I need something like a timeout function to separate the input of a single escape and an escape sequence. Bash's read command has a -t option for it, and the C ncurses lib has the halfdelay/cbreak functions, but how is this possible in sh?