Home > Back-end >  When iterating over Arrays in bash, is there a particular reason using an indexer (i), that you can&
When iterating over Arrays in bash, is there a particular reason using an indexer (i), that you can&

Time:12-12

I am working on making a Calculator App for a class and have run into an issue that I can't google my way out of.

I am making use of bash arrays to process user input (which comes in the form of algebraic expressions (i.e. (5^2)-(13%3)). For the most part, this has gone smooth(ish).

The issue I've recently ran into has to do with an indexing value.

Also, this is a function that is in a file. There is a shebang, I don't want to post the entire file because it is long and the issue is localized to this section of code.

computeNoParens(){

    subExpLength=${#subExp[@]}

    i=0
    op=""

    num1=0
    num2=0  

    for char in ${subExp[@]}
    do
     echo "Char Value at For Start: $char " 

      if [[ $char == "^" ]]; 
      then   
         
         op=$char

         previous=$i-1
             next=$i 1

             num1=${subExp[$previous]}
             num2=${subExp[$next]} **##Issue Occurring here##**

             break;
          fi

        if [[ $char == "*" ]]; 
        then
         op=$char
             let num1=subExp[$((i-1))]
             let num2=subExp[$((i 1))] **##Again##**

        break;
        fi

      if [[ $char == "/" ]]; 
        then
            op=$char    

    etc...

This code is meant to process a sub-array that has been stripped of parentheses. It locates the highest precedence operator and then obtains the two operands that it is between. The if statements work, and it successfully grabs the first operands (num1) and that char representation of the operator. It is when it comes to num2 that the error occurs. Not shown, is "i" increases by 1 each time the for loop iterates. Its highest value never exceeds the greatest index value in the array - 1. I am guessing it has to do with memory, but I cannot access the subsequent array member using any form of i 1, even if i 1 is within the array.

I would greatly appreciate any suggestions on how to obtain that value, otherwise num2 is going to constantly be equal to 0 and my exponents will keep resolving to 1...

Thank you so much for your advice and help, I greatly appreciate it!!!

CodePudding user response:

You can use any arithmetic expression as an array index.

#! /bin/bash

tokens=(12   14)
i=1
echo ${tokens[i-1]}
echo ${tokens[i]}
echo ${tokens[i 1]}

You haven't provided a enter image description here

  • Related