## Display Fibonacci Series

Bash Practice Exercises

# Display Fibonacci Series

Here are a few sample example bash scripts to display the Fibonacci sequence based on a given input.

Time to practice your Bash scripting.

## Exercise

In this Bash practice exercise, write a shell script that accepts a number greater than 3, let's say N. The script prints the Fibonacci sequence with N numbers in the sequence.

### Test data

If you input 5, you should get the following:

``0, 1, 1, 2, 3``

If you input 11, you should get the following:

``0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55``

## What is Fibonacci series?

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers. It starts from 0 and 1, and the sequence is given by: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ....

Each term in the Fibonacci sequence is calculated by adding the previous two terms.

You'll often find Fibonacci series exercises in various programming languages, specially when discussion recursion. Bash scripting is no different.

Some exercises will ask you to start the sequence from a number other than 0 or 1. Basic promise remains the same; each term is a combination for the previous two.

A programming challenge can be solved in more than one way. The solution presented here is for reference purposes only. You may have written a different program and it could be correct as well.

## Solution 1: Fibonacci series in bash without recursive function

Here's a sample bash scripting for Fibonacci sequence that doesn't use recursive function.

``````#!/bin/bash
read -p "Enter number greater than 3: " num

if [ "\$num" -lt 3 ]; then
echo "Number must be greater than 3"
exit
fi

#initialize first and second terms
t1=0
t2=1

#initialize the next term (3rd term)
nextTerm=\$((\$t1 + \$t2))

echo -n "\$t1, \$t2"
fibo () {
for ((i = 3; i <= \$num; ++i)); do
echo -n ", \$nextTerm";
t1=\$t2;
t2=\$nextTerm;
nextTerm=\$((\$t1 + \$t2));
done
echo ""
}

fibo \$num``````

## Solution 2: Fibonacci series using a recursive function in bash

Here's a bash shell script that uses the concept of recursion and function:

``````#!/bin/bash

read -p "Enter number greater than 3: " num

if [ "\$num" -lt 3 ]; then
echo "Number must be greater than 3"
exit
fi

echo -n "Fibonacci series for \$num terms is: "

fibo() {
if [ "\$1" -le 1 ]; then
echo -n "\$1"
else
echo -n \$(( \$(fibo \$((\$1 - 1)) ) + \$(fibo \$((\$1 - 2)) ) ))
fi
}

for (( i=0; i<\$num; ++i)); do
fibo \$i
# Print , and space between the numbers except the last one
if [ "\$i" -lt \$((\$num -1)) ]; then
echo -n ", "
fi
done

echo ""``````

## 📖 Concepts to revise

The solutions discussed here use some terms, commands and concepts and if you are not familiar with them, you should learn more about them.