LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   comparison operator (https://www.linuxquestions.org/questions/linux-newbie-8/comparison-operator-4175417134/)

mmhs 07-17-2012 03:23 AM

comparison operator
 
hi guys
i have a simple question

i want to check integer value in bash scripting

i saw a sample code to check this value it was

if [ $number -eq $number 2>/dev/null ]
then
echo "integer"
else
echo "not integer"
fi

why this sample code works ?

i know we use -eq instead of = to check integer
but my question is how it works $number -eq $number ????

evo2 07-17-2012 03:33 AM

Hi,

it is because test (invoked using "[") will exit with an error (ie non 0) if a non integer argument is passed to -eq.

Evo2.

pan64 07-17-2012 03:51 AM

-eq is the numerical comparison operator, = is the string comparison operator, so:
Quote:

[ 5 -eq 05 ] is true, but
[ 5 = 05 ] is false
otherwise -eq will drop an error message if you try to use it on non-integers.

David the H. 07-17-2012 10:53 AM

What shell are you using? If it's bash, ksh, or another advanced shell, then you could do something like this instead:

Code:

if [[ ${number//[0-9]} ]]; then
        echo "not an integer"
else
        echo "an integer"
fi

${number//[0-9]} removes every digit from the string. If there's anything left over then it's a non-integer value and the test returns true.

Or here's a different way to do it that should work in all bourne-style shells, and is probably more efficient to boot:

Code:

case $number in

        *[^0-9]*) echo "not an integer" ;;
              *) echo "an integer" ;;

esac

In this one it globs the string for non-integer characters.

There are many other ways to go about this as well.


Code:

[ 5 -eq 05 ] is true, but
Numbers that begin with 0 are usually treated as octal values. Using values of 08, or 09 can give you funny results. Interestingly enough, the above pattern works just fine (when using 09) when I use "[", but not when I use "[[".

arithmetic expressions


All times are GMT -5. The time now is 07:26 AM.