2016-10-05 111 views
0

假設我有以下代碼bash腳本

for n in {50..300}; 
do 
((a = 0.3*$n)) 
#do something 
echo $n 
echo $a 
done 

當我運行的代碼,我收到一個錯誤,它說 ((: a = 0.3*50: syntax error: invalid arithmetic operator (error token is ".3*50") 我知道那一定是因爲0.3或任何十進制號碼是不可識別的,或者可能是由於某些格式問題,因爲我以前嘗試((a = $n/2))哪些工作正常,非常感謝,如果任何人都可以給我一個提示。

+1

複製http://stackoverflow.com/questions/3279932/bash-multiplying-decimal-to-int – Nasr

回答

0

雖然這是一個相當不重要的語法問題,但使用shellcheck.net來調試這樣的錯誤會非常有效。你的錯誤行必須像

a=$(echo "0.3*$n" | bc)  # 'echo' to print an arithmetic expression 
           # feeding it to 'bc' for the actual computation. 
+0

@GavyLittlewolf:見http://ss64.com/bash /expr.html用於「expr」的功能。 – Inian

+0

當我嘗試編譯時出現錯誤,它說'a:command not found'這是否意味着我需要聲明變量'a'?但我認爲在bash腳本中我們不需要? –

+0

請將您的腳本粘貼到shellcheck.net中並修復看到的錯誤,從而爲您自己做出嘗試。 – Inian