Bash flush standard input before a read
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"
done
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"
done
fi
Related videos on Youtube
dribler
Real Name: Chris Francy I work as a Senior Network Analyst at Northwest Educational Service District #189 in the Technology Services department. The Technology Service department, in addition to supporting the staff at NWESD, provides network support services to 35 K-12 school districts in Northwest Washington region. In my free time, when I am not at work or answering questions, I play a lot of video games on the PC (Steam Profile).
Updated on September 17, 2022Comments
-
dribler over 1 year
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.
-
dribler about 13 yearsI ended up going with a command like this.
while read -e -t 1; do : ; done
. This seemed to be adequate for what I needed.