Script floating point comparison

Can you suggest me the syntax for floating point comparison in a Bash script? Ideally, I would like to use it as part of an if . Here is a small piece of code:

 key1="12.3" result="12.2" if (( $result <= $key1 )) then # some code here fi 
+16
linux unix bash shell
Mar 11 '10 at 12:18
source share
6 answers

bash does not float, use awk

 key1=12.3 result=12.5 var=$(awk 'BEGIN{ print "'$key1'"<"'$result'" }') # or var=$(awk -v key=$key1 -v result=$result 'BEGIN{print result<key?1:0}') # or var=$(awk 'BEGIN{print "'$result'"<"'$key1'"?1:0}') # or if [ "$var" -eq 1 ];then echo "do something" else echo "result more than key" fi 

there are other shells that can do float, such as zsh or ksh, you can also try to use them.

+14
Mar 11 '10 at 12:21
source share

bc is your friend:

 key1="12.3" result="12.2" if [ $(bc <<< "$result <= $key1") -eq 1 ] then # some code here fi 

Note the slightly obscure line here ( <<< ) as a nice alternative to echo "$result <= $key1" | bc echo "$result <= $key1" | bc .

In addition, un bash -like bc prints 1 for true and 0 for false.

+51
Mar 11 '10 at
source share

another easy way with bc:

 if ((`bc <<< "10.21>12.22"`)); then echo "true"; else echo "false"; fi 
+6
Jun 07 '13 at 12:33
source share

Using the exit() awk function makes it almost readable.

 key1=12.3 result=12.5 # the ! awk is because the logic in boolean tests # is the opposite of the one in shell exit code tests if ! awk "{ exit ($result <= $key1) }" < /dev/null then # some code here fi 

Note that there is no need to reuse the [ operator, since if already uses the output value.

+4
Nov 29 '12 at 10:08
source share
 ### The funny thing about bash is this: > AA=10.3 > BB=10.4 > [[ AA > BB ]] && echo Hello > [[ AA < BB ]] && echo Hello Hello 

Yes, I know this is a hoax, but it works. And scientific notation doesn't work here.

0
Mar 29 '17 at 13:53 on
source share

yu can use this awk comparison inside an if clause, it will print 1 (true) if the condition is true else 0 (false), and these values ​​will be interpreted as booleans using if

 if (( $(awk 'BEGIN {print ("'$result'" <= "'$key1'")}') )); then echo "true" else echo "false" fi 
0
Aug 10 '17 at 9:09 on
source share



All Articles