On 15.12.2012 01:29, gnuist wrote:
> Hi All,
> How do I write a simple recursion function in bash and use its return
> Here is my attempt at a Fibonacci, the file name is
> so I use for function, one more i
> you see a lot of comment outs as there was problem with returning and
> also syntax, whether to use expr `.........` or $((..........))
> For readability, I prefer to use the function name than $0 cryptic,
> which nevertheless refers to the shell script name, not function name.
(No idea what you're asking here. - Just name the file containing the
function with the same name as teh function if you like.)
> please clarify the tradeoff between RETURN and ECHO also.
With 'return' don't expect that you can pass values larger than 127;
function return values are for passing exit status to the caller, not
for returning mathematical function values.
> Any help would be APPRECIATED !!!
if (( n == 0 ))
then printf 0
elif (( n == 1 ))
then printf 1
f1=$( fib $(( n-1 )) )
f2=$( fib $(( n-2 )) )
printf $(( f1 + f2 ))
printf "%s\n" $( fib $1 )
But note two things; first, bash is slooow (compare, e.g., with ksh)
$ time ksh fib.sh 20
$ time bash fib.sh 20
and, second, a recursive solution for fibonacci will quickly get
extremely slow with any shell for any larger parameter value; you
should store already calculated values in an array and access those
instead of calling a function.