Home > other >  writing a guessing game in linux and I keep receiving error message: syntax error near unexpected to
writing a guessing game in linux and I keep receiving error message: syntax error near unexpected to

Time:03-28

Im writing a number guessing game its a bash script in linux. Every time I go to run my code I receive this error message: line 17: syntax error near unexpected token `done'

\#!/bin/bash

random_number= $(( ( RANDOM % 100 )  1 ))
echo $rand
user_guess=0
guesses=0

while \[ $user_guess -ne $random_number \] do
read -p "Enter guess : " ; user_guess
if \["$user_guess" -lt $random_number \] ; then
echo "Select a Higher Number"
elif \[ "$ user_guess" -gt $random_number \]; then
echo "Select a Lower Number"
fi
guesses=$(($guesses   1))
echo "Correct! Guessed $random_number It took $guesses guessess."
done

I tried running my code but was unable to due to error message

CodePudding user response:

there was several syntax errors with your code.

missing ; after while statement no space between [ and $user_guess in the first if statement and a couple more...

also a logic error, the echo correct is in your while loop, so it is always correct even when you don't have the good answer.

adding indentation to your code will help you making it readable.

quotes your variables everywhere you can

other than that, you were on the right track.

#!/bin/bash

RANDOM_NUMBER=$((( RANDOM % 100 )  1 ))
USER_GUESS=0
GUESSES=0

while [[ "$USER_GUESS" -ne "$RANDOM_NUMBER" ]]; do
    read -p "Enter guess : " USER_GUESS
    if [[ "$USER_GUESS" -lt "$RANDOM_NUMBER" ]]; then
        echo "Select a Higher Number"
    elif [[ "$USER_GUESS" -gt "$RANDOM_NUMBER" ]]; then
        echo "Select a Lower Number"
    fi
    GUESSES=$(($GUESSES   1))
done

echo "Correct! Guessed ${RANDOM_NUMBER} It took ${GUESSES} guesses."
  • Related