我有一个场景,我正在计算两个数字的差值。
然后需要在一个范围内检查计算出的差异。
如果位于该范围内,则显示状态为成功,否则显示失败。
下面是我的代码
Range = -1 to 1
var1=12.23
var2=13.23
diff=$(echo "($var1-$var2)"| bc -l)
echo $diff
if [ "$diff" -ge -1 ] && [ "$diff" -le 1 ]; then
echo "$diff" "success"
else
echo "Not within range -1 to 1"
echo "Failure"
fi
错误如下
script.sh: 8: [: Illegal number: -1.00
答案1
如果你想玩,awk
你可以使用如下脚本:
var1=12.23
var2=13.23
echo |awk -v v1=$var1 -v v2=$var2 '{diff=v1-v2;if(diff >= -1 && diff <=1) print diff " success" ;else printf "%s not within range [-1,1]\nFailure\n", diff }'
答案2
shell 无法比较算术上下文中表示浮点值的字符串。但是您可以使用bc
来评估您所计算的布尔(整数)值能在外壳中使用:
#!/bin/bash
val1=12.23
val2=13.23
difference=$( bc -l <<<"$val1 - $val2" )
range_ok=$( bc -l <<<"$difference >= -1 && $difference <= 1" )
if [ "$range_ok" -ne 0 ]; then
printf '%s success\n' "$difference"
else
printf '%s not within range [-1,1]\n' "$difference"
echo "Failure"
fi