1

I have created 5 arrays which contains only floating numbers (contains positive and negative numbers).

Following are the arrays which are declared:

  • assets
  • reported
  • debit
  • credit
  • affiliate
  • loans

I need to perform below formula on the arrays but it's not working.
Is there any other approach?

for((i =1 ; i <(#$assets[@]}; i++));do
echo ${assets[i]} - ( ${reported[i]} + ( ${affiliate[i]} * -1 ) + ${loans[i]} + (${credit[i]} - ${debit[i]})) | bc >> test.log
3
  • 3
    echo "..." | bc >> test.log Commented Jun 16, 2021 at 12:00
  • @blackhole : Is there any other approach. Please assist : Questions about recommendations and opinions are discouraged in Stack Overflow, so I tell you my opinion as a comment, not an answer: I would consider using a shell which can do floating point arithmetic (for instance zsh), or use a programming language with built-in support for float (Ruby, Perl, ....). Commented Jun 16, 2021 at 12:13
  • 1
    Also, you have a syntax error. Run it through shellcheck.net. I think you mean i < ${#assets[@]} Commented Jun 16, 2021 at 14:09

1 Answer 1

5

First thing: bash variables cannot be treated directly as floating point values. Numeric bash values are only integers.

You can use another tool to perform the floating point calculation. i.e. you can use "bc" like you did in your snippet of code.

Your problem is most likely with the parenthesis that are interpreted by bash and not sent to "bc". You have got to build your calculation first as a string before passing it to bc.

I'd write it like this:

echo "${assets[i]} - ( ${reported[i]} + ( ${affiliate[i]} * -1 ) + ${loans[i]} + ( ${credit[i]} - ${debit[i]} ))" | bc
Sign up to request clarification or add additional context in comments.

1 Comment

@JohnKugelman you're right. I initially thought that double quotes would let bash somehow interpret the parenthesis but it does not. So your solution is better.

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.