2016-02-25 178 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

不用謝謝你的幫助 –