8

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

到目前为止,我有这个:

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

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

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

(加上我为了简洁而省略的错误检查代码)

但是,这可能会得到一个空的主题和正文,因为第二个和第三个重定向得到了 EOF。

我一直在尝试用 <&- 和其他东西关闭并重新打开标准输入,但它似乎并没有那样工作。

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

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

4

4 回答 4

6

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

# 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<&-
photos=($(< /dev/stdin))

谢谢!

于 2010-01-02T21:44:07.470 回答
3

您应该能够使用read提示主题和正文:

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

read -rp "Enter message subject" subject

read -rp "Enter message body" body
于 2010-01-02T19:01:12.027 回答
2

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

于 2010-01-02T18:35:49.537 回答
0
# Prompt and read two things from the terminal (not from stdin), then read stdin.
# The last line uses arrays, so is BASH-specific.  The read lines are portable.
# - Ian! D. Allen - idallen@idallen.ca - www.idallen.com
read -p "Enter message subject: " subject </dev/tty
read -p  "Enter message body: " body </dev/tty
photos=($(</dev/stdin))
于 2021-11-06T14:52:15.460 回答