0

So I'm having some trouble with bash / bc math here..

I'm trying to print the filesize in of a backup after I move it to my gdrive via rclone for backup. So I get the filesize via an rclone ls statement with awk print $1 which works great.

In my specific example, I get the value of 1993211 (bytes).

So in my printing code I try to divide this by 1048576 to get it into mb. Which should give me 1.9 mb.

However, $ expr 1993211 / 1048576 | bc -l

prints 1

I've tried various other math options listed here (incl via python / node) and I always get 1 or 1.0. How is this possible?

The calculation should be 1993211 / 1048576 = 1.90087413788

Any idea whats going on here?

ndom91
  • 719
  • 1
  • 9
  • 19
  • This question may be of help https://stackoverflow.com/questions/1253987/how-to-use-expr-on-float – Stedy May 04 '18 at 00:19

2 Answers2

2

That's because it does integer division. Do get floating point division you could run:

bc -l <<< '1993211 / 1048576'

which returns: 1.90087413787841796875

or you can set the number of decimals using scale:

bc -l <<< 'scale=5; 1993211 / 1048576'

which returns: 1.90087

user2968675
  • 781
  • 10
  • 16
2

In the command expr 1993211 / 1048576 | bc -l, expr divides 1993211 by 1048576 using integer division ('cause that's what expr knows how to do), gets "1" as the result, and prints it. bc -l receives that "1" as input, and since there's no operation specified (expr already did that), it just prints it.

What you want is to pass the expression "1993211 / 1048576" directly as input to bc -l:

$ echo "1993211 / 1048576" | bc -l
1.90087413787841796875
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151