0

So yes I am doing this for school but I have most of the script written. I don't know what's going on with it, maybe a syntax error but it keeps messing up(or I do).

The first issue is that it keeps posting the number that you are trying to guess and it says no file or directory(I didn't think I was calling for such things). The 86 is the current random number.

./random: line 14: 86: No such file or directory

The second issue is that the program is telling me guesses are always too low(I can also get them to always be too high)

 I'm thinking of a number between 1 and 100. Your guess:6

./random: line 14: 86: No such file or directory
Sorry, your guess is too low. New guess:87

./random: line 14: 86: No such file or directory
Sorry, your guess is too low. New guess:

Here is my code:

#!/bin/bash


n1=$[($RANDOM % 100) +1]
guesses=1
echo -n "I'm thinking of a number between 1 and 100. Your guess:"

while read n2; do

if   [ $n2 = $n1 ]; then
break;  
else
echo    
if [ $n2 < $n1 ]; then 
echo -n "Sorry, your guess is too high. New guess:"
elif [ $n2 > $n1]; then
echo -n "Sorry, your guess is too low. New guess:"
fi      
fi
guesses=$((guesses+1))

done
echo
echo "Good job! It took you $guesses guesses to get the right number."

Thanks in advance.

troylatroy
  • 135
  • 1
  • 10

1 Answers1

4

Here's the answer as described in the comments above:

#!/bin/bash


n1=$[($RANDOM % 100) +1]
guesses=1
echo -n "I'm thinking of a number between 1 and 100. Your guess:"

while read n2; do

if   [[ $n2 -eq $n1 ]]; then
break;  
else
echo    
if [[ $n2 -gt $n1 ]]; then 
echo -n "Sorry, your guess is too high. New guess:"
elif [[ $n2 -lt $n1 ]]; then
echo -n "Sorry, your guess is too low. New guess:"
fi      
fi
guesses=$((guesses+1))

done
echo
echo "Good job! It took you $guesses guesses to get the right number."

In general you need to pay attention to the error messages bash is giving you:

./random: line 14: 86: No such file or directory

Line 14 is:

if [ $n2 < $n1 ]; then 

and we know $n1 is 86 in this case. So this means the script is attempting to run 86 as if it were a command, hence the file not found error. Why is bash doing this? Well its probably interpreting < as a redirection instead of a greater-than operator. So there is something wrong with the if conditional syntax. Time to dig out the manuals http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
  • The [[ still break the code but it works if you just have a single [. – troylatroy Sep 18 '13 at 22:57
  • Oops, I also forgot to add the space between `$n1` and `]]` in the elif. Edited... now it works with `[[` `]]` as expected. – Digital Trauma Sep 18 '13 at 23:03
  • More reading on the differences between `[` and `[[`: http://stackoverflow.com/questions/13542832/bash-if-difference-between-square-brackets-and-double-square-brackets – Digital Trauma Sep 18 '13 at 23:07