The point of no return

Iterative Bash Script to Generate Fibonacci Series

23rd June 2013 by Ali Erdinç Köroğlu

In mathematics, the Fibonacci series are the numbers in the following integer sequence as 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144..
As you already know that recursion is a function that call itself, too many levels of recursion may crash script with a segfault. So lets write fibonacci series with iterative method.

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
l=1
n=0
for (( i=0; i<=25; i++ ))
do
    echo -n "$n "
    n=$(($n+$l))
    l=$(($n-$l))
done
echo ""

Output and time

erdinc@gauss ~ $ time ./fibo 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025

real    0m0.009s
user    0m0.005s
sys     0m0.003s