Search code examples
bashstdin

reading multiple items semi-interactively from the user in bash


I'm trying to read multiple items from the user 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)

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

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?


Solution

  • # 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 - [email protected] - www.idallen.com
    read -p "Enter message subject: " subject </dev/tty
    read -p  "Enter message body: " body </dev/tty
    photos=($(</dev/stdin))