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 ##
echo "enter the guessing number:"
if [ $num -eq 47 ]; then
echo "That is a right number"
elif [ $num -le 47 ]; then
echo "print higher number"
elif [ $num -ge 47 ]; then
echo "print lower number"
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.