Score:0

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

ph flag

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

Score:2
cn flag

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] ))
Linear Data Structure avatar
ph flag
can you explain why did you change `arr[$i]` with `arr[i]`. I have checked, both term gives the same output
FedKad avatar
cn flag
I think this is coming from Korn Shell. See end of section 6.4.1 at https://docstore.mik.ua/orelly/unix3/korn/ch06_04.htm
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.