I have the following bash script:

# do some time consuming task here
read -p "Give me some input: " input

Now as you might have guessed, if a user presses some random keys during the "time consuming task", the unwanted input is taken into account as well. How do I clear stdin (or at least ignore it) before I issue the read command?

link|improve this question
1  
Myself, unless you are writing a curses-like program, I find what you wish to do to be a design flaw in your program. UNIX/Linux has the very useful feature of buffering input ("type-ahead") and I commonly make use of this functionality. Coming across your program where you throw away what I typed, I would likely submit a bug and stop using your program until it was fixed. – Arcege Apr 29 '11 at 12:13
Some users have annoying habit of playing piano with their keyboard while their program is busy doing something. I would rather throw away those keystrokes and start fresh. But you're right, the "type-ahead" is useful, but not always. – rabin Apr 29 '11 at 15:52
feedback

3 Answers

up vote 2 down vote accepted

I don't think there is a way to clear stdin but (with bash) you can read and discard what is there before you ask for the input

#do some time consuming task here
read -t 1 -n 10000 discard 
read -p "Give me some input: " input

This reads stdin and has a timeout of 1 second, it fails though if there are more than 10000 chars in stdin. I don't know how big you can make the nchars parameter.

link|improve this answer
I actually had found this hack on a forum. I was expecting to find a better way of doing it. Apparently not. – rabin Apr 28 '11 at 16:09
@rabin: If you do find a better way post back here I have it in a few scripts. – Iain Apr 28 '11 at 16:11
feedback
read -d '' -t 0.1 -n 10000

This reads multiple lines of inputs, if the user inadvertently pressed enter multiple times

link|improve this answer
feedback

Enclose the time consuming task in a block whose stdin is closed:

{
     # time consuming task
} <&-

read -p "Give me some input: " input
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.