在bash shell脚本中如何将字符串转换为数字

PJT*_*PJT 12 bash shell

嘿我想将字符串转换为数字

x="0.80"

#I would like to convert x to 0.80 to compare like such:
if[ $x -gt 0.70 ]; then

echo $x >> you_made_it.txt 

fi 
Run Code Online (Sandbox Code Playgroud)

现在我得到错误整数表达式,因为我试图比较一个字符串.

谢谢

gho*_*g74 14

你可以用bc

$ echo "0.8 > 0.7" | bc
1
$ echo "0.8 < 0.7" | bc
0
$ echo ".08 > 0.7" | bc
0
Run Code Online (Sandbox Code Playgroud)

因此,您可以在脚本中检查0或1.


Wil*_*ell 3

出于某种原因,这个解决方案对我很有吸引力:

如果 !回声“$x $y -p”| 直流| grep > /dev/null ^-; 然后
  回显“$x > $y”
别的
  回显“$x <$y”
菲

您需要确保 $x 和 $y 有效(例如仅包含数字和零个或一个“.”),并且根据您的 dc 的年龄,您可能需要指定诸如“10k”之类的内容才能获得它识别非整数值。