Can you please suggest to me the syntax for doing floating point comparison in a Bash script? I would ideally like to use it as part of an if
statement. Here is a small code snippet :
key1="12.3"
result="12.2"
if (( $result <= $key1 ))
then
# some code here
fi
Using the
exit()
function ofawk
makes it almost readable.Note that there is not need to reuse the
[
operator asif
already uses the exit value.bc
is your friend:Note the somewhat obscure here string (
<<<
) notation, as a nice alternative toecho "$result <= $key1" | bc
.Also, the un-bash-like
bc
prints1
for true and0
for false.Yeah, I know it's cheating but it works. And scientific notation does not work here.
yu can use this awk comparison inside a if clause, it will print 1 (true) if the condition is true else 0 (false), and those values will be interpreted as boolean vals by the if
another simple clear way with bc is this:
bash doesn't do floats, use awk
there are other shells that can do floats, like zsh or ksh, you might like to try using them as well