Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

basic comparison-operator question

Status
Not open for further replies.

DoraC

Programmer
May 7, 2002
98
US
Hi,

For some reason I've always thought that to compare numbers in kornshell scripts, you use " -eq ", while for strings you use " == ". In fact, my bolsky/korn book says that the only way to compare strings is with " == ", not " = ", as this is obsolete. However, on our HP UNIX system " == " simply will not work... error messages stating that the == operator was unexpected are returned. " = " does work, however. Some websites advise usage of " -eq " for everything, but this also won't work, as

Code:
    if [[ "1" -eq "1.0" ]]
    then
        echo "they are equal as strings...";
    else
        echo "not equal";
    fi;

returns "they are equal as strings...", which is clearly false. I'm confused... is " = " the accepted, non-obsolete string comparison operator, despite what my book claims?

Thanks,
dora
 
try "hello" -eq "squiggle" ...

just interested to see the outcome ... :)

-eq should be used for numeric comparisons.
= should be used for string comparisons.

(so i believe :)
 
Hi Dora,

in Korn Shell the = only works for string comparison:

#!/bin/ksh

[[ "1" = "1.0" ]] && echo "they are equal as strings..." || echo "they are not equal as strings..."

exit 0

You have other string comparing operators like:

!= not equal

= and != are also working with patterns

-n string if the length of the string is not zero

-z string if the length or the string is zero

You can also use > and < for string comparison.

For integer comparison the following operators are correct:

-eq equal

-ne non-equal

-le less than or equal

-lt less than

-ge greater than or equal

-gt greater than

Hope that helps!

mrjazz [pc2]
 
Thanks everyone! Your responses were helpful...

dora
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top