eXTReMe Tracker
Oct 292012
 

As it turns out the if statement in bash isn’t as friendly towards floating point variables as it is for integer and string variables.

First of all the -gt and -lt switches don’t work.Even the unary operators >,<, etc. don’t work. The only way is to do a comparison between the floating point variables using bc and using the logical outout as a comparison string.

a=11.5; b=11.3
compare_result=`echo "$a >$b" | bc`
 if [ $compare_result -gt 0 ]; then
 echo $a
else
echo $b
 fi

 

  One Response to “Compare floating point variables in BASH”

  1. I have been getting [: -gt: unary operator expected. I used the following and it worked. Hope this helps.
    a=11.5; b=11.3
    compare_result=`echo “$a >$b” | bc`
    if [ -z $compare_result ] # use -n to check for null and -z for non-zero
    then
    echo $a
    else
    echo $b
    fi

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)