在bash中多次读取stdin

时间:2010-01-02 18:20:09

标签: bash stdin

我试图在shell脚本中多次读取stdin,没有运气。目的是首先读取文件列表(从stdin管道读取),然后再读两次以交互式获取两个字符串。 (我要做的是阅读要附加在电子邮件中的文件列表,然后是主题,最后是电子邮件正文。)

到目前为止,我有这个:

photos=($(< /dev/stdin))

echo "Enter message subject"
subject=$(< /dev/stdin)

echo "Enter message body"
body=$(< /dev/stdin)

(加上错误检查代码,我省略了succintness)

然而,这会得到一个空主题和身体,大概是因为第二次和第三次重定向得到了EOF。

我一直试图关闭并重新打开stdin与&lt;&amp; - 和东西,但它似乎没有那样工作。

我甚至尝试使用分隔符作为文件列表,使用“while; read line”循环并在检测到分隔符时跳出循环。但那也不起作用(??)。

任何想法如何构建这样的东西?

3 个答案:

答案 0 :(得分:6)

所以我最终做的是基于ezpz的答案和这个文档:http://www.faqs.org/docs/abs/HTML/io-redirection.html基本上我首先从/ dev / tty提示字段,然后使用dup-and-close技巧读取stdin:

# close stdin after dup'ing it to FD 6
exec 6<&0

# open /dev/tty as stdin
exec 0</dev/tty

# now read the fields
echo "Enter message subject"
read subject
echo "Enter message body"
read body

# done reading interactively; now read from the pipe
exec 0<&6 6<&-
fotos=($(< /dev/stdin))

谢谢!

答案 1 :(得分:3)

您应该可以使用read来提示主题和正文:

photos=($(< /dev/stdin))

read -rp "Enter message subject" subject

read -rp "Enter message body" body

答案 2 :(得分:2)

由于您可能拥有不同数量的照片,为什么不首先提示已知字段,然后阅读“其他所有内容”。它比以交互方式获取未知长度的最后两个字段要容易得多。