3

I have number of arrays in bash, such as arrKey[], aarT[],P[] and I want to do an arithmetic operation with these arrays. As I checked, arrays are working perfectly but, the arithmetic to find array P[] 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]}
1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.