Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Reading input within a while read loop does not seem to work

while read line
do
 echo "get some input from the user"
 read response
done < some_file.txt

execution does not pause like it would had the read been outside the loop. Why is this? Is there a workaround for reading input within a while read loop?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

The problem is that both read line and read response expects (and gets) data from stdin.
This question on SO explains some of it with a link to even more information.

tl;dr
The accepted answer suggests:

Read from the controlling terminal device: read input </dev/tty

share|improve this answer

let the inner read command use stdin, and use a different file descriptor for the while loop

while read -u 3 line; do
  read -p "get some input from the user" response
done 3< some_file.txt
share|improve this answer

Nifle has it exactly right. When you're using multiple terminals, however, you need to be specific.

For those of you coming from google, congratulations on finding this page. If you need to do any user input during a while read loop (this includes rm -i, read, or anything else), you can specify which input pipe to use.

Here's a fragment of this solution that I used:

#in declarations
thistty=$(tty)

lsuser -R LDAP -a home pgrp ALL 2>/dev/null | while read line
do
   homedir=$(echo $homedir | awk -F= '{print $2}')
   sudo rm -ir "$homedir" < $thistty
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.