#!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
#!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
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"}}'
Here is a shorter command using bc -l to compare floating point numbers:
[[ $(bc -l <<< "$d1 >= $d2") -eq 1 ]] && echo "yes" || echo "no"
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.
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
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