bash 在bash中多次读取stdin
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1992323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading stdin multiple times in bash
提问by alvherre
I'm trying to read from stdin multiple times in a shell script, with no luck. The intention is to read a list of files first (which are read from the stdin pipe), and then read twice more to get two strings interactively. (What I'm trying to do is read a list of files to attach in an email, then the subject and finally the email body).
我试图在 shell 脚本中多次从 stdin 读取,但没有运气。目的是首先读取文件列表(从 stdin 管道中读取),然后再读取两次以交互地获取两个字符串。(我要做的是阅读要附加在电子邮件中的文件列表,然后是主题,最后是电子邮件正文)。
So far I have this:
到目前为止,我有这个:
photos=($(< /dev/stdin))
echo "Enter message subject"
subject=$(< /dev/stdin)
echo "Enter message body"
body=$(< /dev/stdin)
(plus error checking code that I omit for succintness)
(加上我为了简洁而省略的错误检查代码)
However, this gets an empty subject and body presumably because the second and third redirections get EOF.
但是,这可能是因为第二次和第三次重定向获得了 EOF,因此主题和正文为空。
I've been trying to close and reopen stdin with <&- and stuff but it doesn't seem to work that way.
我一直在尝试用 <&- 和其他东西关闭并重新打开标准输入,但它似乎并没有那样工作。
I even tried using a separator for the list of files, using a "while; read line" loop and break out of the loop when the separator was detected. But that didn't work either (??).
我什至尝试对文件列表使用分隔符,使用“while; read line”循环并在检测到分隔符时跳出循环。但这也不起作用(??)。
Any ideas how to build something like this?
任何想法如何构建这样的东西?
采纳答案by alvherre
So what I ended up doing is based on ezpz's answer and this doc: http://www.faqs.org/docs/abs/HTML/io-redirection.htmlBasically I prompt for the fields first from /dev/tty, and then read stdin, using the dup-and-close trick:
所以我最终做的是基于 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))
Thanks!
谢谢!
回答by Paused until further notice.
You should be able to use readto prompt for the subject and body:
您应该能够使用read提示输入主题和正文:
photos=($(< /dev/stdin))
read -rp "Enter message subject" subject
read -rp "Enter message body" body
回答by ezpz
Since it is possible that you have a varying number of photos, why not just prompt for the known fields first and then read 'everything else'. It is much easier than trying to get the last two fields of an unknown length in an interactive manner.
由于您可能拥有不同数量的照片,为什么不先提示已知字段,然后阅读“其他所有内容”。这比尝试以交互方式获取未知长度的最后两个字段要容易得多。

