2013-03-05 120 views
0

在脚本中,我想逐行读取一个过程输出,并从用户那里获得确认。到目前为止,我已经做到了这一点:在流水线读取循环中读取键盘输入

mycommand-outputpiped | while (read line) 
do 
    read line 
    #dostuff 

    read confirm #oops -> this read the next item from the pipe, not the keyboard 
done 

于是,我就补充:

read confirm < /dev/stdin 

但它并没有改变的东西,它仍然读取管道下一行... 我该如何处理?

+0

不相关,但为什么在条件列表和循环体中为变量'line'都有'read'命令? – chepner 2013-03-05 17:33:49

+0

我不确定 - 我相信第一次检查时仍有数据要读取,而第二次读取数据。我不知道如何清理它 – bagage 2013-03-05 17:35:11

回答

6

两个read命令从从while环继承了标准输入流中读取。以下应该工作;您的第二次读取需要直接从终端读取,而不是/dev/stdin(这是管道)。

mycommand-outputpiped | while read line 
do 
    # do stuff 
    read confirm < /dev/tty 
done 

注意,只有一个read,在while条件,而且它是用括号括起来(这将创建一个子shell,并line只在子shell,而不是循环可用身体)。