当脚本通过管道输出到shell时如何读取用户输入?

时间:2013-11-22 15:55:44

标签: linux bash

如果我执行以下操作

#!/bin/bash
echo aaa
read -i aaa
echo bbb
echo $aaa

然后按cat test.sh | bash开始,然后我

aaa

没有被要求输入。

问题

脚本必须由cat test.sh | bash启动才能模拟wget -qO - url | bash,如何让用户输入输入?

4 个答案:

答案 0 :(得分:2)

通过运行cat test.sh | bash,用一个连接到cat进程写入内容的管道文件描述符替换bash进程的stdin(通常是终端,因此,“键盘”) test.sh

但是当bash从管道中读取以执行脚本中的命令时,它也会执行read -i aaa,它也会从stdin读取,并且可能会读取bash所指的命令。 / p>

这意味着我们可能在这里有未定义的行为,除非在bash读取其命令的块中指定。

因此,在将脚本传递给shell时,最好不要使用任何消耗脚本中输入的命令。

为什么最终echo $aaa显然只会打印换行符,而不是read读取的内容?因为您不是要说read -i aaa,而只是read aaa

无论如何从stdin读取shell脚本并不常见。只需执行bash test.sh或使用 shebang行

答案 1 :(得分:2)

read builtin从stdin读取,在你的场景中,stdin是cat的重定向输出。当你打电话给它时,它只是试图从猫而不是键盘中读取更多内容。

请尝试以下选项之一阅读:

-e  readline is used to obtain the line.
or
-u FD   Read input from file descriptor FD.

在第二种情况下,我不确定FD的理智值是什么(/ dev /?中的键盘或tty设备)

我甚至不确定你是否可以使用阅读。

答案 2 :(得分:1)

  

The script have to be started by cat test.sh | bash,

为什么? cat会在stdout上打印您的脚本,而不是执行它。

只需执行以下脚本:

bash ./test.sh

更新:根据您的评论:

这也应该有效:

bash <(cat "test.sh")

答案 3 :(得分:0)

使用:

read -i aaa < /dev/tty

从终端读取,而不是shell的标准输入。