0
#!bin/bash

d1=-7
d2=-2

if (( $(awk 'BEGIN {print ("'$d1'" >= "'$d2'")}') )); then
    echo "yes"
    echo "$d1 >= $d2"
else
    echo "no"
fi

Why do I got?

yes
-7 >= -2

Thank

anubhava
  • 761,203
  • 64
  • 569
  • 643
Bom Bam
  • 19
  • 3

5 Answers5

1

You can't simply use shell variables by using $variable_name in awk. You should initialize an awk variable eg--> -v var="$shell_variable" then you could make use of shell variable's values in awk code. Try following awk:

awk -v d1="$d1" -v d2="$d2" 'BEGIN{if(d1>=d2){print "yes";} else {print "no"}}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • actually you can concatenate shell variables in a `awk` one-liner - as long as you set the quotes right (compare numbers - not strings). `-v` is preferable because more readable though, and would he have used it he probably would not have run into the problem in the 1st place. – sborsky Oct 17 '17 at 13:54
1

Here is a shorter command using bc -l to compare floating point numbers:

[[ $(bc -l <<< "$d1 >= $d2") -eq 1 ]] && echo "yes" || echo "no"
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

The double quotes cause awk to perform string comparison, and -7 is lexicographically greater than -2, since 7 comes after 2.

You simply need to invert the single and double quotes so that the double quotes are used by the shell when expanding the variables. That is, instead of

if (( $(awk 'BEGIN {print ("'$d1'" >= "'$d2'")}') )); then

use

if (( $(awk 'BEGIN {print ('"$d1"' >= '"$d2"')}') )); then

However, passing the values into proper awk variables with the -v option is still a better idea.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

No need to do any additional numerical calculation in shell, just let awk set the appropriate exit status and test it with a simple shell if:

$ cat tst.sh
d1=$1
d2=$2

if $( awk -v d1="$d1" -v d2="$d2" 'BEGIN{exit (d1 >= d2 ? 0 : 1)}' ); then
    echo "yes"
    echo "$d1 >= $d2"
else
    echo "no"
fi

$ ./tst.sh -0.5 -0.409
no

$ ./tst.sh -0.5 -0.500
yes
-0.5 >= -0.500

$ ./tst.sh -0.5 -0.501
yes
-0.5 >= -0.501
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

Use just bash:

#!/usr/bin/bash

d1=-7
d2=-2

if (( d1 >= d2 )); then
   echo "yes"
else
   echo "no"
fi

For floats:

#!/usr/bin/bash

d1=-7.6
d2=-2.3

if [ "$(echo ${d1}'>='${d2} | bc -l)" = "1" ]; then
   echo "yes"
else
   echo "no"
fi
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52