Saturday, October 27, 2012

bash script: arithmetic comparison

Arithmetic in BASH is integer math only. You can't do floating point math in Bash; if you need that capability, see Bash FAQ #22.

Remember few tricks

1. use [[ .. ]] for strings and files

2. use (( .. )) for numbers

To compare arithmetic numbers use bc function

$(echo "1.4 < 2.5" | bc)

> and < is for ASCII comparison and so 100 > 75 is false

-gt, -lt is only integer comparison.

This works for me

    if (( $(echo "$mem_util > 75" | bc) == 1 ))
    then
        ...
    fi

I am wondering why there was no floating point support??

References:

http://mywiki.wooledge.org/ArithmeticExpression

http://mywiki.wooledge.org/BashFAQ/031

No comments: