Sunday, January 28, 2024

[SOLVED] Float conditional in bash

Issue

in bash I need to compare two float numbers, one which I define in the script and the other read as paramter, for that I do:

   if [[ $aff -gt 0 ]]
    then
            a=b
            echo "xxx "$aff
            #echo $CX $CY $CZ $aff
    fi

but I get the error:

[[: -309.585300: syntax error: invalid arithmetic operator (error token is ".585300")

What is wrong?

Thanks


Solution

use awk

#!/bin/bash
num1=0.3
num2=0.2
if [ -n "$num1" -a -n "$num2" ];then
  result=$(awk -vn1="$num1" -vn2="$num2" 'BEGIN{print (n1>n2)?1:0 }')
  echo $result
  if [ "$result" -eq 1 ];then
   echo "$num1 greater than $num2"
  fi
fi


Answered By - ghostdog74
Answer Checked By - Willingham (WPSolving Volunteer)