Waffles
Waffles

Reputation: 457

Why can't I read user input properly inside a UNIX while loop?

I'm using the bourne shell in UNIX, and am running into the following problem:

#!/bin/sh


while read line
   do

  echo $line

  if [ $x = "true" ]
  then
        echo "something"
        read choice
        echo $choice
  else
        echo "something"
  fi

done <file.txt

The problem I have here is that UNIX will not wait for user input in the read command - it just plows on through instead of waiting for what the user types in. How can I make unix wait for user input?

Upvotes: 1

Views: 4858

Answers (3)

Matthew Slattery
Matthew Slattery

Reputation: 46998

The redirection of standard input by the <file.txt at the end of while ... done <file.txt affects the whole while loop, including the read choice as well as the read line. It's not just failing to stop - it's consuming a line of your input file too.

Here's one way to solve the problem...

You can save the original standard input by using the somewhat obscure (even by shell standards):

exec 3<&0

which opens file descriptor 3 to refer to the original file descriptor 0, which is the original standard input. (File descriptors 0, 1 and 2 are standard input, output and error respectively.) And then you can redirect just the input of read choice to come from file descriptor 3 by doing read choice <&3.

Complete working script (I wasn't sure where x was supposed to come from, so I just bodged it to make it work):

#!/bin/sh

x=true  # to make the example work

exec 3<&0

while read line
   do

  echo $line

  if [ $x = "true" ]
  then
        echo "something"
        read choice <&3
  else
        echo "something"
  fi

done <file.txt

Upvotes: 2

codaddict
codaddict

Reputation: 455020

It is because you are asking the program to read from the file file.txt:

done <file.txt

Also looks like you have a typo here:

if [ $x = "true" ]
     ^^

which should be "$line".
Also note the ", without them your program will break if the word read from the file has a space in it.

Upvotes: 2

caped_crusader
caped_crusader

Reputation: 1

I don't do much shell scripting, but i think 'read choice' should be 'read $choice'

Upvotes: 0

Related Questions