Mohamed Nuzhy Mohamed Nuzhy - 1 year ago 81
Bash Question

Array arithmetic in bash

I have number of arrays in bash, such as

and I want to do an arithmetic operation with these arrays. As I checked, arrays are working perfectly but, the arithmetic to find array
is wrong.
Can anyone help me with this, please?

#The format is C[0] = (A[0,0]*B[0]) + (A[0,1]*B[1])

this is the code that I tried so far.

P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
echo ${P[0]}

Answer Source

There are several issues with your line of code:

P[0]= $(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
  • There is an additional space after the =, erase it.

    P[0]=$(({arrKey[0,0]} * {arrT[0]} ))+ $(({arrKey[0,1]} * {arrT[1]})) ))
  • It is incorrect to add two elements outside of an Arithmetic expansion.
    Remove the additional parentheses:

    P[0]=$(({arrKey[0,0]} * {arrT[0]} + {arrKey[0,1]} * {arrT[1]}))
  • either use a $ or remove the {…} from variables inside a $(( … )):

    P[0]=$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))
  • Even if not strictly required, it is a good idea to quote your expansions:

    P[0]="$(( arrKey[0,0] * arrT[0] + arrKey[0,1] * arrT[1] ))"

Also, make sure that the arrKey has been declared as an associative array:

declare -A arrKey

To make sure the intended double index 0,0 works.