2 Replies - 1461 Views - Last Post: 16 March 2013 - 09:26 AM Rate Topic: -----

#1 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Intiger expression expected error in bash script

Posted 16 March 2013 - 08:56 AM

I have the following lines of code in bash, and if I run it, my script shows an error in the while loop saying: intiger expression expected, and end the end the result of the execution is wrong.

#!/bin/bash

#
# Parity check
#

echo "Please enter a number: "
read num

if [ $num%2 -eq  0 ];
then
	echo "$num is even!"
else
	echo "$num is odd!"
fi



But if I change my if-statement to this:
if (( $num%2 == 0 ))

then it works nicely.

The point is that I get this error all the time. It doesn't matter whether it is if-statement or while-loop or similar things. I mean if I use the usual comparison keywords from bash and square brackets, it doesn't work. But if I use the other C based comparison signs, and parentheses it works nicely. Is it the problem that I don't use bash-like things correctly?

Is This A Good Question/Topic? 0
  • +

Replies To: Intiger expression expected error in bash script

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2086
  • View blog
  • Posts: 3,173
  • Joined: 21-June 11

Re: Intiger expression expected error in bash script

Posted 16 March 2013 - 09:14 AM

test/[ does not evaluate the operands as of the given operator as arithmetic expressions. It just sees the string 42%2 and notes that that string is not a valid number. You can expr to evaluate arithmetic expresions, so if [ $(expr $num % 2) -eq 0 ] works. Of course using double parentheses works, too, so you might as well keep using that.
Was This Post Helpful? 1
  • +
  • -

#3 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Re: Intiger expression expected error in bash script

Posted 16 March 2013 - 09:26 AM

Thank you very much sepp2k for your helpful and informative reply!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1