vasu buddy vasu buddy - 1 month ago 7
Linux Question

count the number of attempts from an output

This question is in regard to the output of the script,
because I need to know how many attempts I made..

## Guess the Right Number ##

#!/bin/bash
clear

while :

do

echo "enter the guessing number:"

read num

if [ $num -eq 47 ]; then

echo "That is a right number"

break

elif [ $num -le 47 ]; then

echo "print higher number"

elif [ $num -ge 47 ]; then

echo "print lower number"

fi

done


and the following output will be:

enter the guessing number:

23

print higher number

enter the guessing number:

34

print higher number

enter the guessing number:

45

print higher number

enter the guessing number:

47

That is a right number

How do I write code to display an extra line stating how many attempts were made to reach the correct answer?

Answer

You aren't so far off.

This will do it on bash incrementing a variable called $attempts (which starts at 1), each time the wrong answer is attempted.

The loop message uses the $lastmsg variable to make it simple to display the relevant prompt each time.

#!/bin/bash
guessno=47                                        # Set the number to guess
attempts=1                                        # Initial attempts is 1
while true;                                       # Run forever until exit
do
    clear
    echo "$lastmsg"                               # Display last message
    read -p "enter the guessing number" num
    if [[ $num -eq "$guessno" ]]; then
        echo "Correct"
        echo "It took "$attempts" attempt(s)"
        exit                                       # Exit program here
    fi
    if [[ $num -le "$guessno" ]]; then
        lastmsg="print higher number"              # Update $lastmsg
        (( attempts ++ ))
    elif [[ $num -ge "$guessno" ]]; then
        lastmsg="print lower number"               # Update $lastmsg
        (( attempts ++ ))
    fi   
done

Note that the entire program took place inside the endless loop, with the correct answer exiting the program directly.