读取前 Bash 刷新标准输入

Zor*_*che 7 linux scripting bash

在 bash 中是否有一种简单的方法来清除标准输入?

我有一个通常运行的脚本,并且在脚本读取中的某一点用于获取用户的输入。问题是大多数用户通过从基于 Web 的文档复制和粘贴命令行来运行此脚本。它们经常包含一些尾随空格,或者更糟的是,示例命令后面的一些文本。我想调整脚本以在显示提示之前简单地摆脱额外的垃圾。

Mik*_*kel 4

这个线程关于 bash 中的非阻塞 I/O可能会有所帮助。

它建议使用sttydd

或者您可以使用bash read带有-t 0选项的内置函数。

# do your stuff

# discard rest of input before exiting
while read -t 0 notused; do
   read input
   echo "ignoring $input"
done
Run Code Online (Sandbox Code Playgroud)

如果您只想在用户位于终端时执行此操作,请尝试以下操作:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 我最终使用了这样的命令。`同时读取-e -t 1;做 : ; 完成`。这似乎足以满足我的需要。 (2认同)