skip to Main Content

My English is very bad, but i’m try to explain my problem.
I want to create a small program on bash in which the user will have to guess the numbers. But my program has no end.

I’m novice on bash scripting, but i try to get better everyday.
I’m using CentOS 7. I go to /usr/bin/local and create some file, give him chmod +x and open with gedit:

#!/usr/bin/bash

#This script should ask us our name and play the game "Guess the Number" with us.

echo "What is your name?"
read name
echo "Hello $name"
echo "I want to play $ name with you, you have to guess the number from 1 to 10)"
echo "Are you ready?"
read rdy


answer=$(( answer = $RANDOM % 10 ))


read -p "Enter your number: " variant 
     while [ $answer != $variant ]; do

if [ $answer -gt $variant ]; then 
     echo "Your number is bigger, try again"

elif [ $answer -lt $variant ]; then
     echo "Your number is smaller, try again"

  continue

fi

done

eternal "Your number is smaller/bigger"
until you press ctrl+c

What I need to do, please help. I know non amateurs don’t likes novices but i need your help, show me my mistake, and i can get better. Thanks!

2

Answers


  1. #!/bin/bash
    echo "What is your name?"
    read name
    echo "Hello $name"
    echo "I want to play  with you, you have to guess the number from 1 to 10"
    
    
    answer=$(( $RANDOM % 10 ))
    
    while true
    do
        read -p "Enter your number: " variant
        if [ "$answer" -gt "$variant" ]; then
            echo "The number is bigger, try again"
    
        elif [ "$answer" -lt "$variant" ]; then
            echo "The number is smaller, try again"
        else
            break;
        fi
    
    done
    echo "Yes, the answer was ${answer}"
    
    Login or Signup to reply.
  2. You call

    read -p "Enter your number: " variant
    

    before the while loop.

    Inside the loop you never change the variant, so the original value is re-used in the while condition. For Eternity.

    You can start with variant=-1 and move the readinside the loop or do something like @xiawi.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search