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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
blackhole
  • 214
  • 1
  • 11
  • 3
    `echo "..." | bc >> test.log` – Darkman Jun 16 '21 at 12:00
  • @blackhole : _Is there any other approach. Please assist_ : Questions about recommendations and opinions are discouraged in [so], 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, ....). – user1934428 Jun 16 '21 at 12:13
  • 1
    Also, you have a syntax error. Run it through shellcheck.net. I think you mean `i < ${#assets[@]}` – Paul Hodges Jun 16 '21 at 14:09

1 Answers1

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    @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. – Jean-Loup Sabatier Jun 16 '21 at 13:30