If condition is not working and getting error

Hi Team,

If condition is not working properly and getting below error

# ./score1.sh
Enter your score [0-100%] ('q' for quit): 102
Enter your score [0-100%] ('q' for quit): q
./score1.sh: line 9: [: q: integer expression expected
Average is: 102%.
Exit.

Actual code

# Calculate the average of given number.
SCORE=0
AVERAGE=0
SUM=0
NUM=0
while true; do
echo -e  "Enter your score [0-100%] ('q' for quit): \c "
read SCORE;
if [ $SCORE -lt 0  -a $SCORE -gt 100 ]; then
echo "Give correct range "
elif [ $SCORE == q ]; then
echo "Average is: $AVERAGE%."
break
else
SUM=$[$SUM + $SCORE]
NUM=$[$NUM + 1]
AVERAGE=$[$SUM / $NUM]
fi
done
echo "Exit."

Thanks
Torrid.

The line if [ $SCORE -lt 0 -a $SCORE -gt 100 ]; then is looking to compare integers. You are giving it letter, which it cannot handle. You would be better to put the quit-test before it.

That said, you also don't check that someone enters the value b or Hello world! in there.

Is this a homework exercise?

Robin

you were partially correct robin.

I am new to shell script and learning through online. when I search for help I got this forum and posted my query.

if made a change in IF statement it is working fine

if [[ $SCORE -gt 100 || $SCORE -lt 0  ]] ; then 

but getting below error when i give 09 as input

./score1.sh
Enter your score [0-100%] ('q' for quit): 09
./score1.sh: line 12: [[: 09: value too great for base (error token is "09")
./score1.sh: line 12: [[: 09: value too great for base (error token is "09")
./score1.sh: line 18: 0 + 09: value too great for base (error token is "09")
Exit.

I think he's totally correct. Although you changed the mechanism to evaluate the conditional expression, you still try to do integer calculations / comparisons with string values which may not result in a syntax error, but is a logical one. Avoid that by following his/her advice "to put the quit-test before it".

Some shells (including sh and bash ) interpret integers with leading zeroes as octal numbers, so 09 can't be evaluated. bash allows the base specification by adding e.g. a leading 10# .

2 Likes