1

I have tried all possible combinations that I could find to compare a real and an integer, but they all seemed to fail.

For example

if (( "10.0" == "10" )); then
    echo "Joy"
else
    echo "Damn it"
fi

I tried square brackets, I tried without quotes, I tried -eq, but that was for integers only. So not sure how I am supposed to make this work in bash.

Peter Raeves
  • 516
  • 1
  • 4
  • 17
  • Bash doesn't do floating point comparisons. [`bc`](http://www.gnu.org/software/bc/manual/html_chapter/bc_toc.html) is the standard unix system tool for doing arithmetic or comparisons using floating point numbers. – John B Aug 15 '14 at 11:08
  • Or use a shell that does support floating-point, like ksh93. – cdarke Aug 15 '14 at 12:52

2 Answers2

2

Using bc:

if [[ $(echo "10.0 == 10" | bc) -eq 1 ]]; then
    echo "Joy"
else
    echo "Damn it"
fi

awk is also possible:

if awk -v op="10.0" 'BEGIN { exit !(op == 10) }'; then
konsolebox
  • 72,135
  • 12
  • 99
  • 105
1

Convert both to float and make string comparison:

printf -v a "%f" 10.0
printf -v b "%f" 10
echo $a
echo $b

Output:

10.000000
10.000000
Cyrus
  • 84,225
  • 14
  • 89
  • 153