Reputation: 1188
Warning: I just started learning bash recently and trying to do a recursive function that will calculate a term...so...
x0 = 0 x1 = 1 xm = 3 * xm-1 - 2 * xm-2
The function I wrote so far is:
#!/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
But I get some strange errors...and not sure if I did it correctly...can anyone tell me what causes these issues and correct my code so it works? Thank you so much.
Errors:
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 "=")
Upvotes: 0
Views: 808
Reputation: 784958
Well not sure about your calculation but your syntactically cleaned up base script is this one:
#!/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
Upvotes: 3