Compare strings as integers

  • Follow


Hello,

I have 2 strings in a script (sh) that I want to compare. The two
strings are parsed from a version number.

num1=1
num2=2

I want to do the following:

if [ $num1 > $num2 ] ; then

But fails, how can I do this using the sh shell. Is there some
conversion routine.

Thanks,
Enda
0
Reply keepyourstupidspam 4/22/2005 9:41:33 AM

Enda Mannioooo wrote:

> I want to do the following:
> if [ $num1 > $num2 ] ; then

man test
You need to replace > by -gt.
By the way, it feels strange reeding a shell script with more $ than ".
0
Reply Marc 4/22/2005 9:54:36 AM


Hi,

Thanks for replying but the operator -dt does not solve this for me
because I am working with strings not integers, integers are stored in
the strings.

doing:

imag=2
kmaj=3

if [ $imaj -gt $kmaj ] ; then
    exit 1
elif [ $imaj -lt $kmaj ] ; then
    echo "works"
fi


gives me:

../test.sh: [: -gt: unary operator expected
../test.sh: [: -lt: unary operator expected

0
Reply keepyourstupidspam 4/22/2005 12:57:46 PM

keepyourstupidspam@yahoo.co.uk wrote:

> imag=2
     ^
> kmaj=3
> 
> if [ $imaj -gt $kmaj ] ; then
           ^

I believe this is the reason.
0
Reply Marc 4/22/2005 1:12:01 PM

In article <1114174665.930810.296940@l41g2000cwc.googlegroups.com>,
 keepyourstupidspam@yahoo.co.uk wrote:

> Hi,
> 
> Thanks for replying but the operator -dt does not solve this for me

You misspelled -gt

> because I am working with strings not integers, integers are stored in
> the strings.
> 
> doing:
> 
> imag=2

You misspelled "imaj".

I think you need to get some more sleep, your fingers are fumbling like 
crazy.

> kmaj=3
> 
> if [ $imaj -gt $kmaj ] ; then
>     exit 1
> elif [ $imaj -lt $kmaj ] ; then
>     echo "works"
> fi
> 
> 
> gives me:
> 
> ./test.sh: [: -gt: unary operator expected
> ./test.sh: [: -lt: unary operator expected

If you'd run your script with the -x option you would have seen that the 
problem was that the variable wasn't being expanded as you expected.  
Can't people do the least bit of debugging before posting?  You're a 
programmer, act like it!

-- 
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
0
Reply Barry 4/22/2005 1:29:14 PM

4 Replies
516 Views

(page loaded in 0.174 seconds)

Similiar Articles:













7/26/2012 3:07:44 AM


Reply: