阅读在bash标准输入多次 [英] reading stdin multiple times in bash

查看:231
本文介绍了阅读在bash标准输入多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个shell脚本标准输入多次,但没有运气阅读。我们的目的是先读取文件的列表(这是从标准输入管道读取),然后读取两次拿到两个字符串交互。 (我试图做的是阅读文件的列表以电子邮件的附加,那么这个问题终于电子邮件正文)。

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).

到目前为止,我有这样的:

So far I have this:

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

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

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

(加上错误检查code,我省略succintness)

(plus error checking code that I omit for succintness)

不过,这是因为第二和第三重定向得到EOF得到一个空的主题和正文presumably。

However, this gets an empty subject and body presumably because the second and third redirections get EOF.

我一直在试图关闭并以&lt重新打开标准输入;&安培; - 之类的东西,但它似乎并没有工作的方式。

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 (??).

任何想法如何建立这样的事情?

Any ideas how to build something like this?

推荐答案

那么,我落得这样做是基于EZPZ的答案,这个文档:<一href=\"http://www.faqs.org/docs/abs/HTML/io-redirection.html\">http://www.faqs.org/docs/abs/HTML/io-redirection.html基本上我提示首先从/ dev / tty的领域,然后读取标准输入,使用DUP和近距离的技巧:

So what I ended up doing is based on ezpz's answer and this doc: http://www.faqs.org/docs/abs/HTML/io-redirection.html Basically I prompt for the fields first from /dev/tty, and then read stdin, using the dup-and-close trick:

# 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))

谢谢!

这篇关于阅读在bash标准输入多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆