bash:刷新标准输入(标准输入)

rah*_*hul 4 bash stdin flush

我有一个bash脚本,我主要在交互模式下使用.但是,有时我会在脚本中输入一些输入.在循环中处理stdin之后,我使用"-i"(交互式)复制文件.但是,这永远不会被执行(在管道模式下),因为(我猜)标准输入还没有被刷新.为简化示例:

#!/bin/bash
while read line
do
    echo $line
done
# the next line does not execute 
cp -i afile bfile
Run Code Online (Sandbox Code Playgroud)

将其放在t.sh中,并执行:ls | ./t.sh

不执行读取.我需要在读取之前刷新stdin.怎么会这样呢?

unb*_*eli 6

这与冲洗无关.你的标准输出是ls的输出,你已经用你的while循环阅读了所有这些,所以read立即得到EOF.如果你想从终端阅读一些东西,你可以试试这个:

#!/bin/bash
while read line
do
    echo $line
done
# the next line does execute 
read -p "y/n" x < /dev/tty
echo "got $x"
Run Code Online (Sandbox Code Playgroud)

  • @mouviciel不,$(tty)无法工作。试试吧 ;) (2认同)