25

The bash read command is very convenient for:

  • read -p to prompt the user and capture input from the user
  • while read loop to iterate through the lines of a file.

However, I'm having issues attempting to do both simultaneously.

For example:

#!/bin/bash

while read item
do

    echo Item: $item

    read -p "choose wisely: " choice

    echo You still have made a $choice.

done < /tmp/item.list 

Rather than blocking and standing by for the user to enter a choice, bash is populating $choice with the next item in the item.list file.

Does bash support doing a read nested within a read loop?

ddoxey
  • 2,013
  • 1
  • 18
  • 25
  • 1
    The two things to keep in mind are 1) the inner loop inherits its file descriptors from the outer loop, and 2) you can use other file descriptors than standard input. – chepner Apr 30 '13 at 20:44
  • possible duplicate of [bash: nested interactive read within a loop that's also using read](http://stackoverflow.com/questions/11704353/bash-nested-interactive-read-within-a-loop-thats-also-using-read) – Sparhawk Jul 30 '14 at 07:03

1 Answers1

37

The simplest fix is to have the outer read read from a different file descriptor instead of standard input. In Bash, the -u option make that a little easier.

while read -u 3 item
do
  # other stuff
  read -p "choose wisely: " choice
  # other stuff
done 3< /tmp/item.list
Zombo
  • 1
  • 62
  • 391
  • 407
  • 5
    Just changing `read -p "choose wisely: " choice` to `read -p "choose wisely: " choice < /dev/tty` should also work. – dvlcube Jul 31 '19 at 18:39