浮动有条件的bash

Ope*_*way 5 bash

在bash中我需要比较两个浮点数,一个我在脚本中定义,另一个读作参数,为此我做了:

   if [[ $aff -gt 0 ]]
    then
            a=b
            echo "xxx "$aff
            #echo $CX $CY $CZ $aff
    fi
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

[[:-309.585300:语法错误:无效算术运算符(错误标记为".585300"))

怎么了?

谢谢

小智 7

使用bc而不是awk:

float1='0.43255'
float2='0.801222'

if [[ $(echo "if (${float1} > ${float2}) 1 else 0" | bc) -eq 1 ]]; then
   echo "${float1} > ${float2}"
else
   echo "${float1} <= ${float2}"
fi
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 5

使用 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
Run Code Online (Sandbox Code Playgroud)