Tuesday, January 11, 2005

Shell script performing comparisons on decimals

It recently came to my attention you cannot make use of typical numeric comparison operators -gt -lt -eq -ne on float point numbers.

The test case

#!/bin/bash

one=1.2
two=2.1

if [ $one -lt $two ]; then
echo "One is smaller than two"
fi

The error you'll produce will go like: "bash: [: 1.2: integer expression expected"

So you need to make use of ascii comparison operators in order to work around this problem. I'm not sure of all the implications of such an action, but for the cases I needed it to work it did :)

So your test would end up looking something like

one=1.2
two=2.1
if [[ "$one" < "$two" ]]; then
echo "One is smaller than two"
fi

Note: You need to make use of double "[" or escape the comparison operator otherwise the shell will interpret the comparison operator as an input redirector, and you'll end up with an error like: "bash: 2.1]: No such file or directory".

0 Comments:

Post a Comment

<< Home