1753706 Members
4645 Online
108799 Solutions
New Discussion юеВ

script question

 
SOLVED
Go to solution
Ridzuan Zakaria
Frequent Advisor

script question

Hi,

I am trying to compare 2 numerical values using test command (i.e -ge, -gt).

However when comparing 2 big values the test command return incorrect result. Below example return KS0 greater than KS1. The result should be the other way around. Thanks.

Example:

KS0=524288000
KS1=4294967295

if [ $KS0 -gt $KS1 ]; then
echo "$KS0"
fi
quest for perfections
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor

Re: script question

Your second operand exceeds the maximum value for a signed 32-bit integer. You will need to use bc to evaluate this expression.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: script question

Here is one technique that should work; the idea is that we will invoke bc (which can handle arbitrarily large values) and use it to return -1,0, or 1 depending on whether arg1 is less than, equal to, or greater then arg2.

#!/usr/bin/sh

compare()
{
typeset -i10 RSLT=0
typeset A=${1}
typeset B=${2}
shift 2
RSLT=$(echo "a=${A}; b=${B}; r=0; if (a < b) r=(-1)l if (a > b) r=1; r" | bc)
echo "${RSLT}"
return 0
} # compare

typeset -i10 CMP=$(compare ${KS0} ${KS1})
if [[ ${CMP} -ge 0 ]]
then
echo "KS0 GE KS1"
else
echo "KS0 LT KS1"
fi
If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: script question

Another option is to do a string compare-

typeset -RZ10 KS0X=$KS0
typeset -RZ10 KS1X=$KS1
if [ $KS0X > $KS1X ] ; then
echo "$KS0"
fi

By using typeset to right-justify zero fill the value, then a string compare will work.

HTH

-- Rod Hills
There be dragons...
A. Clay Stephenson
Acclaimed Contributor

Re: script question

One correction that should me made is to allow for the evaluation of negative numbers by bc. The arguments need to be enclosed in ()'s and I also see one typo. "l" should be ";".

compare()
{
typeset -i10 RSLT=0
typeset A=${1}
typeset B=${2}
shift 2
RSLT=$(echo "scale=8; a=(${A}); b=(${B}); r=0; if (a < b) r=(-1); if (a > b) r=1; r" | bc)
echo "${RSLT}"
return 0
} # compare

That should now compare any combination of numerical values including floating point values (up to 8 decimal places set by scale=8) as well as integers.
If it ain't broke, I can fix that.