views:

37

answers:

3

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?

A: 

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

caped_crusader
+2  A: 

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.

codaddict
A: 

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
Matthew Slattery