我试图在shell脚本中多次读取stdin,没有运气.目的是首先读取文件列表(从stdin管道读取),然后再读两次以交互式获取两个字符串.(我要做的是阅读要附加在电子邮件中的文件列表,然后是主题,最后是电子邮件正文).
到目前为止我有这个:
photos=($(< /dev/stdin))
echo "Enter message subject"
subject=$(< /dev/stdin)
echo "Enter message body"
body=$(< /dev/stdin)
Run Code Online (Sandbox Code Playgroud)
(加上错误检查代码我省略了succintness)
然而,这可能是因为第二次和第三次重定向得到EOF而得到一个空的主体和身体.
我一直试图关闭并重新打开stdin与<& - 和东西,但它似乎没有那样工作.
我甚至尝试使用分隔符作为文件列表,使用"while; read line"循环并在检测到分隔符时中断循环.但那也不起作用(??).
任何想法如何建立这样的东西?
所以我最终做的是基于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))
Run Code Online (Sandbox Code Playgroud)
谢谢!
# 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))
Run Code Online (Sandbox Code Playgroud)