bash脚本上的奇怪错误

时间:2012-03-26 21:36:41

标签: linux bash function recursion

警告:我刚刚开始学习bash并试图做一个递归函数来计算一个术语......所以......

x0 = 0 x1 = 1 xm = 3 * xm-1 - 2 * xm-2

到目前为止我写的函数是:

#!/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 "=")

1 个答案:

答案 0 :(得分: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