Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there an easy way in bash to flush out the standard input?

I have a script that is commonly run, and at one point in the script read is used to get input from the user. The problem is that most users run this script by copying and pasting the command line from web-based documentation. They frequently include some trailing whitespace, or worse, some of the text following the sample command. I want to adjust the script to simply get rid of the extra junk before displaying the prompt.

share|improve this question
up vote 2 down vote accepted

This thread on nonblocking I/O in bash might help.

It suggests using stty and dd.

Or you could use the bash read builtin with the -t 0 option.

# do your stuff

# discard rest of input before exiting
while read -t 0 notused; do
   read input
   echo "ignoring $input"

If you only want to do it if the user is at a terminal, try this:

# if we are at a terminal, discard rest of input before exiting
if test -t 0; then
    while read -t 0 notused; do
       read input
       echo "ignoring $input"
share|improve this answer
I ended up going with a command like this. while read -e -t 1; do : ; done. This seemed to be adequate for what I needed. – Zoredache Feb 11 '11 at 7:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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