3

Here is my task: read some data from file line by line. For each line, if it satisfies some condition, then ask user to input something and proceed based on the user's input.

I know how to read content line-by-line from a shell script:

while read line; do
   echo $line
done < file.txt

However, what if I want to interact with the user inside the loop body. Conceptually, here is what I want:

while read line; do
    echo "Is this what you want: $line [Y]es/[n]o"
    # Here is the problem:
    # I want to read something from standard input here.
    # However, inside the loop body, the standard input is redirected to file.txt
    read INPUT
    if [[ $INPUT == "Y" ]]; then
       echo $line
    fi
done < file.txt

Should I use another way to read file? or another way to read stdin?

monnand
  • 395
  • 1
  • 3
  • 8

1 Answers1

9

You can open the file on a file descriptor other than standard input. For example:

while read -u 3 line; do     # read from fd 3
  read -p "Y or N: " INPUT   # read from standard input
  if [[ $INPUT == "Y" ]]; then
    echo $line
  fi
done 3< file.txt             # open file on fd 3 for input
ooga
  • 15,423
  • 2
  • 20
  • 21