0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Print Fibonacci Series

Use a Bash script with a loop and variables to print the Fibonacci series, for example: n=10; a=0; b=1; for ((i=0; i.
📋

Examples

Inputn=1
Output0
Inputn=5
Output0 1 1 2 3
Inputn=0
Output
🧠

How to Think About It

To print the Fibonacci series, start with two numbers 0 and 1. Then repeatedly add the last two numbers to get the next one. Print each number until you reach the desired count.
📐

Algorithm

1
Get the number of terms to print (n).
2
Initialize two variables with 0 and 1 for the first two Fibonacci numbers.
3
Repeat n times: print the current number, calculate the next by adding the last two, then update the variables.
4
Stop after printing n numbers.
💻

Code

bash
n=10
a=0
b=1
for ((i=0; i<n; i++))
do
  echo -n "$a "
  fn=$((a + b))
  a=$b
  b=$fn
done
Output
0 1 1 2 3 5 8 13 21 34
🔍

Dry Run

Let's trace n=5 through the code

1

Start

n=5, a=0, b=1

2

Iteration 1

Print 0, fn=0+1=1, a=1, b=1

3

Iteration 2

Print 1, fn=1+1=2, a=1, b=2

IterationabPrinted
0010
1111
2121
3232
4353
💡

Why This Works

Step 1: Initialize variables

Start with a=0 and b=1 as the first two Fibonacci numbers.

Step 2: Print current number

Print the value of a which holds the current Fibonacci number.

Step 3: Calculate next number

Add a and b to get the next Fibonacci number and update a and b accordingly.

🔄

Alternative Approaches

Recursive function
bash
fib() {
  if (( $1 <= 1 )); then
    echo $1
  else
    echo $(( $(fib $(( $1 - 1 ))) + $(fib $(( $1 - 2 ))) ))
  fi
}
for ((i=0; i<10; i++)); do fib $i; done
Uses recursion but is slower and less efficient for large n.
Using an array
bash
fib=(0 1)
for ((i=2; i<10; i++)); do
  fib[i]=$(( fib[i-1] + fib[i-2] ))
done
for i in "${fib[@]}"; do echo -n "$i "; done
Stores all Fibonacci numbers in an array for later use but uses more memory.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs n times, each step does constant work, so time is O(n).

Space Complexity

Only a few variables are used, so space is O(1).

Which Approach is Fastest?

The iterative loop is fastest and most memory efficient compared to recursion or array storage.

ApproachTimeSpaceBest For
Iterative loopO(n)O(1)Simple and efficient for all n
Recursive functionO(2^n)O(n)Educational but slow for large n
Array storageO(n)O(n)When you need all Fibonacci numbers stored
💡
Use echo -n to print numbers on the same line separated by spaces.
⚠️
Forgetting to update both variables a and b correctly after each iteration.