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

时间:2010-06-18 07:55:20

标签: 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

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

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

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

我不确定是否可以在此处执行您想要的操作(即让read从用户那里获取输入而不是ls)。问题是脚本的所有标准输入都来自管道,句点。这是相同的文件描述符,因此它不会因为你想要它而“切换”到终端。

一种选择是将ls作为脚本的子项运行,如下所示:

#!/bin/bash

ls | while read line
do
    echo $line
done

read -p "y/n" x
echo "got $x"