Clear stdin before reading
In Bash 4, you can set -t
(timeout) to 0
. In this case, read
immediately returns with an exit status indicating whether there's data waiting or not:
# do some time consuming task here
while read -r -t 0; do read -r; done
read -p "Give me some input: " input
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.
read -d '' -t 0.1 -n 10000
This reads multiple lines of inputs, if the user inadvertently pressed enter multiple times