1829575 Members
2734 Online
109992 Solutions
New Discussion

Reading single keypress

 
SOLVED
Go to solution
Mary Rice
Frequent Advisor

Reading single keypress

Hello Guys,

I need a way to read a single keypress from a script. For example, is there an easy way to determinine if the user has pressed 'Y' or 'N' while not requiring the Carriage Return to be pressed? I tried various tricks with the stty command but nothing seems to work. Please help.

Thank you, Mary
2 REPLIES 2
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Reading single keypress

Hi Mary:

There is no simple way to do this from the shell but there is a small C program I've used for a very long time. It does an ioctl to disable the line-buffered input mode. If the status of the command is 0 then your character is output to stdout. This indicates that the character was in the printable range ' ' thru '~'; if the character was outside the range ' ' thru '~' then the exit status is the character. It then restores the keyboard for normal input. Note: This program does not recognize multi-character sequences; you will get only the first character of such a sequence.


Use it like this:

echo "Enter a character: \c"
CH=$(onechar)
echo
STAT=$?
if [ ${STAT} -eq 0 ]
then
echo "You pressed \"${CH}\""
else
echo "Your character was not printable"
echo "ASCII Value = ${STAT}"
fi

Compile the attached code like this:

cc onechar.c -o onechar

It's K & R C so it will compile with the bundled C compiler.

Regards, Clay
If it ain't broke, I can fix that.
Olav Baadsvik
Esteemed Contributor

Re: Reading single keypress


Hi,

Here is a way to do it. Not very elegant
perhaps, but it works:

#!/bin/sh
echo -n "Enter a character: \c"
stty raw
WHOAMI=$(who am i)
TTY=$(echo $WHOAMI | cut -f 2 -d " ")
readchar=`dd if=/dev/$TTY bs=1 count=1 2>/dev/null`
stty -raw
echo ""
echo "Thank you for typing a $readchar ."

Regards
Olav