0

Please help. How can accomplish this

if [ echo `awk 'BEGIN{print 0.001>0.9}'` -eq 0 ]; then DO SOMETHING; fi

But that is wrong.
What I'm trying to do is: if the first number(0.001) if greater than 0.9 then DO SOMETHING. else DO NOTHING
The numbers will always be float like 0.001, 0.03, 0.89 etc...
Ah and I MUST NOT use the bc command.

andresg3
  • 343
  • 2
  • 6
  • 20
  • What is the source of the first number? Clearly, 0.001 is never greater than 0.9, so you must have some variable you intend to compare to 0.9. – chepner Nov 22 '13 at 19:45

4 Answers4

5

To generalize it:

function gt {
    awk -v n1=$1 -v n2=$2 'BEGIN {exit !(n1 > n2)}'
}

if gt 0.01 0.9; then
    do_something
fi
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

This should work:

[[ $(awk 'BEGIN{print (0.001>0.9)}') -eq 0 ]] && DO SOMETHING

Or if you want to pass variables to awk:

[[ $(awk -v a='0.001' -v b='0.9' 'BEGIN{print (a>b)}') -eq 0 ]] && echo "a is smaller"
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Taking your existing code, and it's lack of variables, literally, then this should suffice:

DO SOMETHING

Since 0.001 is never greater than 0.9, awk should print 0, which of course is equal to 0, and so the whole test is a little pointless without using any variables...

twalberg
  • 59,951
  • 11
  • 89
  • 84
1
$ cat ./tst.sh
function cmp {
    awk -v v1="$1" -v v2="$2" 'BEGIN{
        if      (v1 > v2) { diff =  1 }
        else if (v1 < v2) { diff = -1 }
        else              { diff =  0 }
        print diff
    }'
}

if [ $(cmp "$1" "$2") -eq  1 ]; then rslt="is greater than"; fi
if [ $(cmp "$1" "$2") -eq -1 ]; then rslt="is less than";    fi
if [ $(cmp "$1" "$2") -eq  0 ]; then rslt="is equal to";     fi

printf "%s %s %s\n" "$1" "$rslt" "$2"

$ ./tst.sh 0.001 0.9
0.001 is less than 0.9

$ ./tst.sh 0.9 0.001    
0.9 is greater than 0.001

$ ./tst.sh 0.9 0.9000
0.9 is equal to 0.9000
Ed Morton
  • 188,023
  • 17
  • 78
  • 185