Why do I get bash integer expression error from [ ${guess[0]} -eq num ]? -
i trying prompt user guess value between 0-9. getting error integer expression expected. don't understand why can explain going wrong?
num=8 echo "enter value between 0-9" read -a guess if [ ${guess[0]} -eq num ] ; echo "you guesses right number" elif [ ${guess[0]} -gt num ] ; echo "you guessed high" elif [ ${guess[0]} -lt num ] ; echo "you guess low" fi
to make minimum number of changes necessary code run correctly:
#!/bin/sh num=8 echo "enter value between 0-9" read guess if [ "$guess" -eq "$num" ] ; echo "you guesses right number" elif [ "$guess" -gt "$num" ] ; echo "you guessed high" elif [ "$guess" -lt "$num" ] ; echo "you guess low" fi
notes:
- since you're reading single value, no compelling reason use array -- easy take out
-a
argumentread
; doing makes code compatible posix sh, ,#!/bin/sh
on systems posix-compliant shells. - you need expand variables when using
test
(or[
).$num
, not bare$num
; latter possible in numeric context, whereastest
regular command as parser concerned -- doesn't create special context @ syntax level. - because
[
regular command, need spaces after it, other command name. - because
[
regular command, need spaces before]
expects last argument -- same when passing arguments else. - if shell bash (your script started
#!/bin/bash
), use math context:if (( guess == num ))
, orif (( guess > num ))
. is math context, , has special parsing rules.