0

I want to compare the input and text file word.

The text file has:

one 
two
three

Run time input assigned to a variable var:

read -p " enter the value : " var
while read first
do
  a=$first
  if [ "$a" == "$var" ] 
  then 
    echo  " $var is found "
  else
    echo " $var is not found "
    read -p " please enter correct value " $var
  fi
done < word.txt

I tried above code in my script, but it is not working.

  • What do you want the script to do? Currently, the user has to guess the data of the first line. If they fail, they have to guess the data on the second line. If the succeed, the next line is read, and if that's not correct, the user has to guess the data on the third line. Could you please describe what the script is supposed to do? – Kusalananda Jul 30 '18 at 7:07
  • That's is correct only. but this code is not working – Kannan M Jul 30 '18 at 7:23
  • it should check both text file word and user input . if it is not match, it will ask for correct input from user. – Kannan M Jul 30 '18 at 7:26
  • why $var in read command ? read -r " please enter correct value " $var – Kamaraj Jul 30 '18 at 8:04
  • mistakenly i mentioned -r..it is changed now..if the $var value is wrong.. it will ask for new value.and again it will check the value – Kannan M Jul 30 '18 at 9:38
0

I'm not entirely sure what the flow should look like in your code, so I'll give two versions:

  1. The user guesses until they correctly guess the current word in the file, then moves on to guess the second word, and so on.

  2. The user guesses the current word, and moves on to the next regardless of whether the guess was correct or not.

The first variation:

exec 3<&1
n=0
while read word; do
    n=$(( n + 1 ))
    while true; do
        printf 'Word #%d\n' "$n"
        read -p 'guess the word: ' -u 3 guess
        if [ "$guess" = "$word" ]; then
            echo 'correct'
            break
        fi
        echo 'wrong, try again'
    done
done <words
exec 3<&-

We can't just read inside the loop as that would read from the file. Instead we read from filedescriptor 3, which is a copy of standard input made before the loop. After the loop, this filedescriptor is closed.

The inner while loop iterates until a correct guess is made.

The second variation:

exec 3<&1
n=0
while read word; do
    n=$(( n + 1 ))
    printf 'Word #%d\n' "$n"
    read -p 'guess the word: ' -u 3 guess
    if [ "$guess" = "$word" ]; then
        echo 'correct'
    else
        echo 'wrong, next word...'
    fi
done <words
exec 3<&-

This is similar to the previous code, but without the inner while loop.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.