0

I need to read lines from a file. Usually send the file in via stdin, but if I also need to do user input, I can't!

Here's a (contrived) example:

#!/usr/bin/env bash

cat <<HERE >/tmp/mytemp.txt
four of clubs
two of hearts
queen of spades
HERE

while read line ; do
  echo "CARD: $line"
  read -p 'Is that your card? ' answer
  echo "YOUR ANSWER: $answer"
  echo
done </tmp/mytemp.txt

This doesn't work. Instead you get this:

$ ~/bin/sample_script.sh
LINE: four of clubs
MY ANSWER: two of hearts

LINE: queen of spades
MY ANSWER: 

$

How can I do both in the same loop?

TomOnTime
  • 4,175
  • 4
  • 36
  • 39

1 Answers1

3

Use two different file descriptors.

while IFS= read -r -u 3 from_file; do
  read -r from_user
  # ...your logic here...
done 3< filename

Or, to not depend on any bash extensions:

while IFS= read -r from_file <&3; do
  read -r from_user
done 3< filename

(The explicit -r and clearing of IFS are necessary to read contents without trimming trailing whitespace, expanding backslash escapes, etc; their use is a good habit to be in by default unless you explicitly know that you want these behaviors).

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441