3

Here is my task: read some data from file line by line. For each line, if it satisfies some condition, then ask user to input something and proceed based on the user's input.

I know how to read content line-by-line from a shell script:

while read line; do echo $line done < file.txt 

However, what if I want to interact with the user inside the loop body. Conceptually, here is what I want:

while read line; do echo "Is this what you want: $line [Y]es/[n]o" # Here is the problem: # I want to read something from standard input here. # However, inside the loop body, the standard input is redirected to file.txt read INPUT if [[ $INPUT == "Y" ]]; then echo $line fi done < file.txt 

Should I use another way to read file? or another way to read stdin?

1

1 Answer 1

9

You can open the file on a file descriptor other than standard input. For example:

while read -u 3 line; do # read from fd 3 read -p "Y or N: " INPUT # read from standard input if [[ $INPUT == "Y" ]]; then echo $line fi done 3< file.txt # open file on fd 3 for input 
Sign up to request clarification or add additional context in comments.

4 Comments

@monnand Great! I've added closing fd 3 at the end and changed the opening command from input/output to just input.
You can also just redirect the loop's standard input, rather than use a pair of execs: while read -u 3 line; do ...; done 3< file.txt.
done <3 file.txt is incorrect, it should be done 3< file.txt
@DavidŠmíd Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.