Read from user inside a while statement

Hi there
I want to ask to a user something about each line of a file. This is my code:

#cat test.txt
first line
second line
third line
#cat test.sh
#!/bin/ksh
read_write () {
echo "Do you want to print the line (YES/NO)?\n"

read TEST
case ${TEST} in
        YES) return 0;;
        NO) return 1;;
        *) read_write;;
esac
}

while read _line 
do
        read_write
done < ./test.txt

but when i run it:

#test.sh
Do you want to print the line (YES/NO)?

[...]

Do you want to print the line (YES/NO)?

./test.sh[7]: read_write: recursion too deep

How can I solve it?

Thanks in advance.

---------- Post updated at 04:46 PM ---------- Previous update was at 04:40 PM ----------

All right, I found the solution (I promise that I had search before I posted)

Sorry for the format, but the site doesn't allow me to publish urls

stdin has already been redirected from file so stdin is no longer the keyboard. You'll need to save a copy of stdin in order to use it elsewhere but how to do that depends on what variant of what shell you have. What is it? What's your system?

Solaris 8
ksh

read_write () 
{
echo -n "Do you want to print the line (Y/N)?"
<&5 read  TEST   # input from handler 5 = org. stdin
case "$TEST" in
        Y) return 0;;
        N) return 1;;
        *) read_write;;
esac
}

exec 4< ./test.txt  # handler 4 for file
exec 5<&1    # handler 5 is same as stdin handler 1
while read line   
do
        echo $line      # stdout
        read_write
done <&4
1 Like