[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: bash is not capable of comparing of strings and real numbers
From: |
DennisW |
Subject: |
Re: bash is not capable of comparing of strings and real numbers |
Date: |
Mon, 7 Dec 2009 17:08:02 -0800 (PST) |
User-agent: |
G2/1.0 |
On Dec 7, 4:22 pm, pk <p...@pk.invalid> wrote:
> phani krishna jampala wrote:
> > bash is not capable of comparing of strings ( imean interms of lessthan or
> > greater than etc)
>
> It is, if you use [[ ]]
>
> a="abcd"
> b="bcde"
> if [[ "$b" > "$a" ]]; then
> echo "$b is greater than $a"
> fi
>
> > and real numbers ( the float values).
>
> True, but I can't really speak as to whether this is planned or not (I think
> it isn't, but of course I might be wrong).
Since printf understands floats (or acts like it does), you can use it
plus a little care and luck to do float comparisons in Bash:
$ a=.3
$ b=0.2
$ [[ $a < $b ]] && echo true || echo false
true # WRONG
$ printf -v a "%0.2f" $a
$ printf -v b "%0.2f" $b
$ [[ $a < $b ]] && echo true || echo false
false # CORRECT
echo "$a $b"
0.30 0.20
$ a=147.1
$ b=23
$ [[ $a < $b ]] && echo true || echo false
true # WRONG
$ printf -v a "%08.2f" $a
$ printf -v b "%08.2f" $b
$ [[ $a < $b ]] && echo true || echo false
false # CORRECT
echo "$a $b"
00147.10 00023.00