2016-02-25 80 views
8

这里是我的脚本,其相当不言自明:“无效的算术运算符”在bash做浮点运算

d1=0.003 
d2=0.0008 
d1d2=$((d1 + d2)) 

mean1=7 
mean2=5 
meandiff=$((mean1 - mean2)) 

echo $meandiff 
echo $d1d2 

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

+1

顺便说一句,如果您从bash切换到ksh93,浮点将本机可用。 –

回答

15

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)) 
+0

当我将算法更改为format = $((echo“”| bc))时,它仍然抱怨? –

+1

这是一个错字,很抱歉。应该是'$(...)',而不是'$((...))'。命令替换和算术扩展有点过于相似。 – chepner

+0

不用谢谢你的帮助 –