Clear stdin before reading

Solution 1:

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.

Solution 2:

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

Solution 3:

function clear_stdin()
(
    old_tty_settings=`stty -g`
    stty -icanon min 0 time 0

    while read none; do :; done 

    stty "$old_tty_settings"
)

clear_stdin

Solution 4:

read -d '' -t 0.1 -n 10000

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