The main problem my code doesn't do echo every time(fibonacci sequence)
#!/bin/bash
function fib(){
if [ $1 -le 0 ]; then
echo 0
elif [ $1 -eq 1 ]; then
echo 1
else
echo $[`fib $[$1 - 2]` `fib $[$1 - 1]` ]
fi
}
fib $1
i was expecting it will do echo every time. It shows:
~/Bash$ ./fn.sh 12
144
but i need it to show like this:
~/Bash$ ./fn.sh 12
0
1
1
2
3
5
8
13
21
34
55
89
144
CodePudding user response:
Your function is consuming the output of its invocation via backticks (command substitution). Only the last output is sent to the terminal. Your function will only return the n-th number of the Fibonacci sequence.
If you want to return all the numbers of the sequence up to a certain point, you can use a loop:
for i in $(seq "$i"); do
fib "$i"
done
CodePudding user response:
Another method might be:
#!/bin/bash
fibseq () {
echo "$1"
if (($3 > 0)); then fibseq "$2" $(($1 $2)) $(($3 - 1)); fi
}
if (($1 > 0)); then fibseq 0 1 "$1"; fi
Note that this is just a loop disguised as recursion. This method is much more efficient than the naive recursive version to compute Fibonacci sequences. Arguments to fibseq
function: $3
serves as a counter, $1
and $2
are the last two Fibonacci numbers.
As an aside note, you can replace the $(($1 $2))
with $(bc <<< "$1 $2")
if you want arbitrary-precision arithmetic.