Clearing the input buffer before a read.

Martin Weitzel martin at mwtech.UUCP
Tue Nov 27 07:13:40 AEST 1990


In article <1990Nov26.001425.15563 at massey.ac.nz> K.Spagnolo at massey.ac.nz (Ken Spagnolo) writes:
>I have an sh script that asks the user a question and reads
>the answer into a variable in the usual method.  I want to
>be able to flush the input buffer just before the read so
>that any slips or double key bounces get ignored, rather than
>used as the answer.  I realize this disables type ahead, but
>I can live with that.  Anyone know how to do this?

The exact answer depends on your variant of UNIX. Check the ioctl(2)
and/or termio(7) entry of your manual. Usually it describes some method
of how to clear the input buffer. Then write a small C-program (usually
a two-liner) and call that program before executing the read-command
of the shell. On the system I use (ISC UNIX 2.2) such a flush-program
could look like:

#include <termio.h>
main() { (void) ioctl(0, TCFLSH, 0); return 0; }

Alternatively, (and as you have to call a program anyway), you may choose
to let your program read one line of input, and assign this input within
the script by means of the `.....` construct. To save some more typing, you
should include the desired prompt as an argument of your program. Instead
of:
	echo "now> \c"	# send prompt to the user
	flush		# your program to flush input buffer
	read var	# read user's input into var
use
	var=`readline 'now> '`

Here is a very simple version of a readline-program:

#include <termio.h>
#define MAXLINE 80
main(argc, argv)
	int argc; char *argv[];
{
	char buffer[MAXLINE]; int n;
	if (argc > 1) write(1, argv[1], strlen(argv[1]));
	(void) ioctl(0, TCFLSH, 0);
	n = read(0, buffer, MAXLINE);
	if (n <= 0) return 1;
	(void) write(1, buffer, n-1);
	return 0;
}

With more work, (considerably more work, if you want it portable) you
could even add more or less simple editing functions to this program.
(I've done so long time ago, using the termcap database to specify
cursor-keys and control-codes, but the resulting program is too large
to be posted here.)
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.shell mailing list