“无效的算术运算符”在bash中做浮点运算

这是我的脚本,它不言自明:

d1=0.003 d2=0.0008 d1d2=$((d1 + d2)) mean1=7 mean2=5 meandiff=$((mean1 - mean2)) echo $meandiff echo $d1d2 

但不是得到我的预期输出:0.0038 2我得到错误Invalid Arithmetic Operator, (error token is ".003")?

bash不支持浮点运算。 你需要使用像bc这样的外部工具。

 # Like everything else in shell, these are strings, not # floating-point values d1=0.003 d2=0.0008 # bc parses its input to perform math d1d2=$(echo "$d1 + $d2" | bc) # These, too, are strings (not integers) mean1=7 mean2=5 # $((...)) is a built-in construct that can parse # its contents as integers; valid identifiers # are recursively resolved as variables. meandiff=$((mean1 - mean2))