读取前清除标准输入

读取前清除标准输入

我有以下 bash 脚本:

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

现在您可能已经猜到了,如果用户在“耗时任务”期间按下一些随机键,则不需要的输入也会被考虑在内。如何stdin在发出读取命令之前清除(或至少忽略)它?

答案1

我不认为有办法清除 stdin,但(使用 bash)你可以在要求输入之前读取并丢弃那里的内容

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

这会读取 stdin,超时时间为 1 秒,但如果 stdin 中的字符超过 10000 个,则会失败。我不知道 nchars 参数可以设置多大。

答案2

在 Bash 4 中,你可以将-t(timeout) 设置为0。在这种情况下,read立即返回退出状态,指示是否有数据在等待:

# do some time consuming task here
while read -r -t 0; do read -r; done
read -p "Give me some input: " input

答案3

read -d '' -t 0.1 -n 10000

如果用户无意中多次按下回车键,这将读取多行输入

答案4

这对我来说很有效:

function clean_stdin()
{
    while read -e -t 0.1; do : ; done
}

相关内容