2

I have a file "in" that contains:

a
b
c

I run the following command:

cat in | while read el; do select yn in "yes" "no"; do echo $yn; done; done;

And get the following output:

1) yes
2) no
#?
#? 
#? 

What I want is to be able to type 1 or 2 at each iteration. What do I need to do differently to make this work?

2 Answers 2

2

You're piping input into a while loop. Within the loop, stdin comes from the preceding command, not from the console. Your select statement is reading from the same pipe that the read statement is reading from.

Also, you don't need cat.

You need to preserve stdin for use in the select statement. Try this:

while read el; do select yn in "yes" "no"; do echo $yn; break; 
done <&4; done 4<&0 < in

First, note that we're redirecting input using '<', rather than using cat.

This preserves your origin stdin (fd 0) in fd 4, and then inside the loop redirects input to select from fd 4.

2
  • Very cool, this definitely works. Is there a way to do it with a pipe? The reason being is that my original input comes from a series of commands instead of a flat file. I can definitely write the output to a file and redirect from the new file, but I'm curious how to do it with a pipe. Dec 25, 2009 at 19:49
  • Yeah, you can do the same thing with a pipe. In either case (using "<" or "|") you're just redirecting stdin. Try this: (cat input | while read el; do select yn in "yes" "no"; do echo $yn; break; done <&4; done) 4<&0
    – larsks
    Dec 26, 2009 at 2:02
-1

select will read an input and execute it repeatedly until EOF; what you almost certainly want is the superficially similar:

cat in | while read el; do select yn in "yes" "no"; do echo $yn; break; done; done
3
  • It still doesn't prompt me for the select and only presents the prompt twice. I'm still don't get the behavior I want. Dec 24, 2009 at 1:45
  • Works For Me (TM)
    – womble
    Dec 24, 2009 at 2:06
  • It doesn't work for me. I get all output at once and it doesn't wait for input. Similar to what the OP's version does, just sort of in a different order. Dec 24, 2009 at 2:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .