0

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 "=")

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

it's working just for 5, for 3 it shows -6 and for 6 it shows 0. :-(
Sorry, your code is correct but var3=$((3*(var1-2)*var2)) is wrong, it should be $(( (3*var1) - (2*var2) ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.