2012-03-26 222 views
0

警告奇怪的錯誤* XM-1 - 2 * XM-2在bash腳本

我寫了到目前爲止的功能是:

#!/bin/bash 
calculate() 
{ 
if [ $1 -eq 0 ] 
then 
echo "0" 
fi 
if [ $1 -eq 1 ] 
then 
echo "1" 
fi 
if [ $1 -ge 1 ] 
then 
let var1 = `calculate [ $1-1 ]`; 
let var2 = `calculate [ $1-2 ]`; 
let var3 = 3*var1-2*var2; 
echo var3 
fi 
} 
calculate 3 

但我得到一些奇怪的錯誤...不知道我是否正確地做到了......能任何人告訴我是什麼原因導致這些問題,並糾正我的代碼,使其工作?非常感謝。

錯誤:

TP1p1.sh: line 4: [: [: integer expression expected 
TP1p1.sh: line 8: [: [: integer expression expected 
TP1p1.sh: line 12: [: [: integer expression expected 
TP1p1.sh: line 14: let: =: syntax error: operand expected (error token is "=") 
TP1p1.sh: line 4: [: [: integer expression expected 
TP1p1.sh: line 8: [: [: integer expression expected 
TP1p1.sh: line 12: [: [: integer expression expected 
TP1p1.sh: line 15: let: =: syntax error: operand expected (error token is "=") 
TP1p1.sh: line 16: let: =: syntax error: operand expected (error token is "=") 

回答

3

嘛不知道你的計算,但你的語法清理基地腳本是這一個:

#!/bin/bash 
calculate() { 
if [ $1 -eq 0 ]; then 
    echo -n "0" 
elif [ $1 -eq 1 ]; then 
    echo -n "1" 
elif [ $1 -ge 1 ]; then 
    var1=$(calculate $(($1-1))) 
    var2=$(calculate $(($1-2))) 
    var3=$((3*(var1-2)*var2)) 
    echo $var3 
fi 
} 
calculate 5 
+0

它的工作只是爲5,3這表明-6和6顯示0. :-( – FinalDestiny 2012-03-26 22:05:20

+0

對不起,你的代碼是正確的,但var3 = $((3 *(var1-2)* var2)) 是錯誤的,它應該是$(((3 * var1) - (2 * var2))) – FinalDestiny 2012-03-26 22:44:20

+0

無論如何,你們幫助我學到了很多東西,非常感謝。 – FinalDestiny 2012-03-26 22:44:58