I keep Getting error: 'arr[$i] is not a valid identifier' on bash script

I'm practicing Fibonacci series on bash script with arrays and for loop but I got this error

jrnl6T2.sh: line 10: `arr[$i]': not a valid identifier

Here is .sh file

#! /bin/bash

read -p "Enter term: " term

arr[0]=0
arr[1]=1
for (( i=2; i<$term; i++))
do

    arr[$i]= expr $((arr[$i-2]+arr[$i-1]))
    
done

for (( j=0; j<$term; j++ ))
do
    echo ${arr[$j]}
    
done

As I'm a beginner so not sure why I am getting this error. I have google this problem also but did not find appropriate solution. I am using ubuntu 20.04.3


Solution 1:

You are doing two wrong things in the expression calculation statement:

  1. You have put a space character after the = sign. You cannot use whitespace before or after the equals sign.

  2. expr is a command. To capture and assign its output, you need to enclose it in $(), like this:

    arr[i]=$(expr $((arr[i-2]+arr[i-1])))
    

    or

    arr[i]=$(expr ${arr[i-2]} + ${arr[i-1]})
    

    Please note that the expr command in the first case does nothing; the $(()) construct calculates the expression.

However, I suggest you do Bash arithmetic operations using the let command.

Your script can be corrected like this:

#!/bin/bash
read -p "Enter term: " term
let arr[0]=0
let arr[1]=1
for (( i=2; i<term; i++ ))
do
  let arr[i]=arr[i-2]+arr[i-1]
done
for (( j=0; j<term; j++ ))
do
  echo ${arr[j]}
done

Another alternative (which is equivalent to the let command, but I would not prefer) is this:

arr[i]=$(( arr[i-2] + arr[i-1] ))