在流水线读取循环中读取键盘输入

bag*_*age 0 unix bash sh

在脚本中,我想逐行读取流程输出,并获得用户的确认.到目前为止我已经这样做了:

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

   read confirm #oops -> this read the next item from the pipe, not the keyboard
done
Run Code Online (Sandbox Code Playgroud)

所以我试着添加:

read confirm < /dev/stdin
Run Code Online (Sandbox Code Playgroud)

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

che*_*ner 8

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

mycommand-outputpiped | while read line
do
    # do stuff
    read confirm < /dev/tty
done
Run Code Online (Sandbox Code Playgroud)

请注意read,在while条件中只有一个,并且它没有括在括号中(这将创建一个子shell,并且line只能在子shell中使用,而不是循环体).