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. Commented Feb 16, 2016 at 8:19
  • @123 Thanks . Do you have any suggestion for Decimal values (Float)? Commented Feb 16, 2016 at 8:25
  • You can use bc or awk. Commented Feb 16, 2016 at 8:27
  • please suggest, in this case how can I use bc/awk command? Commented Feb 16, 2016 at 9:32
  • First example - you said: "I am surprised here the result is False." I am surprised too, because ksh returns True Commented Feb 16, 2016 at 13:02

1 Answer 1

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 Commented Feb 16, 2016 at 14:46
  • what shell do you have? I ve checked it on bash and ksh. Commented Feb 16, 2016 at 17:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.