Operating System - HP-UX
1829125 Members
2200 Online
109986 Solutions
New Discussion

Reading a single character ... then what?

 
SOLVED
Go to solution
A. Daniel King_1
Super Advisor

Reading a single character ... then what?

Hi, folks.

I see here a clever trick:

http://forums.itrc.hp.com/cm/QuestionAnswer/1,,0x1be0fef4d250d611abdb0090277a778c,00.html

This is where stty/dd/tty are used to read a single character from the keyboard.

stty raw
readchar=$(dd if=$(tty) bs=1 count=1 2>/dev/null)
stty -raw

But now, in our cut-and-paste world, what happens if someone pastes a string? How does one nullify or clear the remaining input before accepting another keystroke? Especially if the remaining characters are of a random nature and may or may not be \n-terminated?

In other words, how do I clear the keyboard buffer in ksh?

Thanks in advnace.
Command-Line Junkie
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: Reading a single character ... then what?

Hi:

See if this would begin to address your needs:

#!/usr/bin/sh
stty -echo
stty raw
#
readchar=$(dd if=$(tty) bs=1 count=1 2>/dev/null)
stty -raw
echo "you typed '${readchar}'"
#
stty raw
line -t 1 RSVP #...bit_bucket anything more...
#
stty sane
stty erase "^H"
exit 0

Regards!

...JRF...
A. Daniel King_1
Super Advisor

Re: Reading a single character ... then what?

Thanks, James!

Almost exactly what I had in mind!

Any ideas on how to get the timeout down to null?
Command-Line Junkie
James R. Ferguson
Acclaimed Contributor

Re: Reading a single character ... then what?

Hi (again):

Sorry, the timeout value for 'line' must be an integer greater than zero for this hack to work.

The following is a little shorter, safer prototype and will restore sensible shell terminal I/O behavior should the process be killed:

#!/usr/bin/sh
trap 'stty sane erase "^H"; exit 2' 0 1 2 3 15
#
stty -echo raw
readchar=$(dd if=$(tty) bs=1 count=1 2>/dev/null)
#
stty -raw
echo "you typed '${readchar}'"
#
stty raw
line -t 1 RSVP #...bit_bucket anything more...
#
exit 0

Regards!

...JRF...
A. Daniel King_1
Super Advisor

Re: Reading a single character ... then what?

Thanks, again. Always a pleasure, James.
Command-Line Junkie
James R. Ferguson
Acclaimed Contributor

Re: Reading a single character ... then what?

Hi (again):

/No_Points_Please/

You bring interesting questions! Thank you; it's my pleasure.

Warmest regards!

...JRF...