0

I am trying to do a simple dictionary of words inserted by user which are collected in txt file and then the function to learn them. Words in two different languages are seperated by a chosen seperator and then checked if the answer typed by user is correct. I've had a problem with the txt file lines being skipped after first iteration so I used a subshell, which works fine, if I didn't have a variables counting correct/wrong answers in it. I don't really know how to solve this. My piece of code:

count=0
ans=0
while IFS= read -r line; do
    (...)
    (                     # without subshell the lines from txt file were skipped
    exec 0< /dev/tty      # I used this command to prevent skipping the "read check" line 
                          # as it happened before 
    read check
    if [ "$check" == "$correct" ];then
        echo "Correct"
        let ans++
        let count++
    else
        echo "Wrong"
        let count++
    fi
    )
done < "file.txt"
echo "Answered $ans out of $count words correctly"
4
  • The read can be confused, when the file you read is simultaneously updated.
    – White Owl
    Jun 17 at 15:38
  • The redirection < "file.txt" outside the loop sets the stdin of the whole loop. exec 0< /dev/tty would set stdin again, overriding the redirection. If you put the exec in a subshell, the redirection there only applies to the subshell.
    – ilkkachu
    Jun 17 at 16:07
  • 2
    You might want to put the redirection of the file in some other fd, e.g. while IFS= read -r <&3; do ... done 3< file.txt
    – ilkkachu
    Jun 17 at 16:08
  • @ilkkachu thanks it it worked just fine
    – ebeebe
    Jun 18 at 0:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.