1

Today I was trying to compare two values and surprised what I saw. I didn't find any good suggestion anywhere. Could any one please help?

if [ 10.94 -gt 10 ]
then
  echo True
else
  echo False
fi

I am surprised here the result is False.

Then I tried the following.

if [[ 10.94 > 10 ]]

Result came as True. I was fine with it.

Again my script gave a flaw at a particular condition like below

if [[ 5.15 > 10 ]]
  echo True
fi

Here result came as True.

How come? Is there any better idea, which will compare the decimal values in a proper way?

6
  • > is a string comparison, -gt is arithmetic and only accepts integers. – 123 Feb 16 '16 at 8:19
  • @123 Thanks . Do you have any suggestion for Decimal values (Float)? – PriB Feb 16 '16 at 8:25
  • You can use bc or awk. – 123 Feb 16 '16 at 8:27
  • please suggest, in this case how can I use bc/awk command? – PriB Feb 16 '16 at 9:32
  • First example - you said: "I am surprised here the result is False." I am surprised too, because ksh returns True – techraf Feb 16 '16 at 13:02
1
echo | awk '{if (10.1 > 10.0) {print "True"} else {print "False"} }' 
True

if [ $(echo "10.12 < 10.13"|bc -l) -eq 1 ];then echo "True"; else echo "False"; fi
True
2
  • Hopefully the first solution will work in my script. The 2nd solution is not working in my shell. I ll try the first one. Thanks – PriB Feb 16 '16 at 14:46
  • what shell do you have? I ve checked it on bash and ksh. – jai_s Feb 16 '16 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.