views:

232

answers:

2

Hello,

Can you please suggest me the syntax for doing floating point comparison in shell script. I am using bash.

I would ideally like to use as part of if statement

here is a small code snippet :

key1="12.3" result="12.2"

 if (( $result <= $key1 ))
    then
# some code here
fi

thanks

Kiran

+4  A: 

bash doesn't do floats, use awk

key1=12.3
result=12.5
var=$(awk 'BEGIN{exit "'$key1'"<"'$result'"}')    
# or var=$(awk -vkey="$key1" -vresult="$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 floats, like zsh or ksh, you might like to try using them as well

ghostdog74
+1, or perl, or ...
roe
Thanks GhostDog74, Your comments did help.. you have been a great support..Thanks everyone
Kiran
This looks like a rather awkward way to do it (no pun intended).
Sorpigal
+5  A: 

bc is your friend:

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

Note the somewhat obscure here string (<<<) notation, as a nice alternative to echo "$result <= $key1" | bc.

Also, the un-bash-like bc prints 1 for true and 0 for false.

Chen Levy
Vow.. This is good..
Kiran
bc (or even dc) is good for this, and is certainly easier to read than the awk method, but doing it this way requires a subshell (or a pipe). In terms of efficiency expr is better and I find it easier to read, too. But still, +1 for bc!
Sorpigal
if what you meant by "easier to read than awk" means its shorter, that's because I am separating shell variables against awk variables. I can also write it like `var=$(awk 'BEGIN{print "'$result'"<"'$key1'"?1:0}')`
ghostdog74
Even if you do that it's quite verbose. Quotes inside quotes and a ternary operator? I'm sure you see what I mean.
Sorpigal