Reading stdin several times in bash

I am trying to read from stdin several times in a shell script, with no luck. The intention is to first read the list of files (which are read from the stdin channel), and then read twice to get two lines interactively. (What I'm trying to do is read the list of files to attach via email, then the subject, and finally the body of the email).

So far I have this:

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

(plus the error checking code that I omit for succintness)

However, this gets the empty object and the body supposedly because the second and third redirects receive EOF.

I'm trying to close and reopen stdin with <& - and stuff, but it doesn't seem to work.

I even tried using a separator for a list of files using a while while read read loop and breaking out of a loop when a separator was detected. But that didn't work either (??).

Any ideas how to build something like this?

+5
bash stdin
Jan 02 '09 at 18:20
source share
3 answers

So what I did in the end is based on the answer of ezpz and this document: http://www.faqs.org/docs/abs/HTML/io-redirection.html Basically I request 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)) 

Thank!

+5
Jan 02 '09 at 21:44
source share

You can use read to request an object and a body:

 photos=($(< /dev/stdin)) read -rp "Enter message subject" subject read -rp "Enter message body" body 
+3
Jan 02 '09 at 19:01
source share

Since it’s possible that you have a different number of photos, why not just request the known fields first and then read “everything else”. This is much simpler than trying to get the last two fields of unknown length interactively.

+2
Jan 02 '09 at 18:35
source share



All Articles