在while循环中读取bash中的输入

w2l*_*ame 93 bash while-loop

我有一个bash脚本,如下所示,

cat filename | while read line
do
    read input;
    echo $input;
done
Run Code Online (Sandbox Code Playgroud)

但这显然没有给我正确的输出,因为当我在while循环中读取它时,它试图从文件文件名读取,因为可能的I/O重定向.

还有其他方法吗?

小智 97

从控制终端设备读取:

read input </dev/tty
Run Code Online (Sandbox Code Playgroud)

更多信息:http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

  • -1,因为这将绕过任何其他重定向.例如,`bash yourscript </ foo/bar`将等待用户输入,这仅在读取密码时才可接受.@GordonDavisson的答案适用于所有其他用途. (11认同)

Gor*_*son 53

您可以将常规stdin重定向到单元3以保持将其放入管道中:

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你真的使用cat这种方式,用一个重定向替换它会变得更容易:

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished
Run Code Online (Sandbox Code Playgroud)

或者,您可以在该版本中交换stdin和unit 3 - 使用单元3读取文件,然后单独保留stdin:

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished
Run Code Online (Sandbox Code Playgroud)

  • @LucaBorrione:你好吗?它是否在等待你给它输入(请注意`read line`是从notify-finished读取的,但如果你只是按照写的那样运行`read -u 3 input`正在从控制台读取)? (2认同)