0

This is a simple school project. The console keeps stating [5:command not found

#!/bin/bash

num=28
echo "Guess a number a number between 1 and 100"
read guess

while [$guess -ne $num]
do

 if [$guess -lt $num]
 then
     echo "number is higher"
 elif [$guess -gt $num]
 then
     echo "number is lower"
  else
     echo "Correct! The number is $number"
  fi

done
rici
  • 234,347
  • 28
  • 237
  • 341
keebler
  • 1
  • 1
  • You need to turn on command tracing to see what you are doing. You haven't quoted the script, so I have to guess about command separation, but I do not think there is command separation before the "read" command (i.e. a semicolon or a new line). Anyway, add a "set -x" line. – Bruce K Oct 02 '15 at 22:55

2 Answers2

2
while [$guess -ne $num]

is interpreted by first expanding the parameters:

while [5 -ne 28]

which then causes the command [5 to be executed, passing it arguments -ne and 28]

You wanted to execute the command [, so you needed to write:

while [ $guess -ne $num ]

(Note the spaces around both [ and ]. Without the space, the characters become part of another word.)

Ditto with the statements following if and elif.

rici
  • 234,347
  • 28
  • 237
  • 341
  • thank you. I didn't realize it needed spacing to understand the condition – keebler Oct 05 '15 at 23:27
  • @keebler: the important takeaway is that `[` is a _command_. As a character, it is not special; `[23` would be a different command, which you could implement as an executable file with that name. If you look around, probably in `/usr/bin`, you'll find a file named `[`. – rici Oct 06 '15 at 01:50
0

Do this:

#!/bin/bash
num=28
echo "Guess a number a number between 1 and 100" 
read guess

while [ $guess -ne $num ]; do
  if [ $guess -lt $num ]
  then
    echo "number is higher" 
    read guess
  elif [ $guess -gt $num ]
  then
    echo "number is lower" 
    read guess
  fi
done
echo "Correct! The number is $number" 
amath
  • 1,279
  • 9
  • 14