1

Can someone assist with my handling this calculation that I need in bash?

Currently I have the following:

Size=$((IPS * DataPages / (1024 * 1024 * 1024) * 1.05))

But I get the following error when trying to execute:

./buffer: line 20: IPS * DataPages / (1024 * 1024 * 1024) * 1.05: syntax error: invalid arithmetic operator (error token is ".05")

I'm open to using other alternatives, like either print or awk or even bc, but I need some guidance.

user3299633
  • 2,473
  • 2
  • 21
  • 38

2 Answers2

2

bash does not support floating point arithmetic. Use bc for that. To enabled floating point arithmetic in bc pass the --mathlib (or -l) option:

IPS=2
DataPages=3
bc --mathlib <<< "($IPS * $DataPages / (1024 * 1024 * 1024) * 1.05)"

To capture that into a shell variable use process substitution:

...
Size=$(bc --mathlib <<< "($IPS * $DataPages / (1024 * 1024 * 1024) * 1.05)")
hek2mgl
  • 143,113
  • 25
  • 227
  • 253
0

(( )) doesn't support floating point arithmetic. Use bc or awk.

using bc

Size=$( echo "scale=2; $IPS * $DataPages / (1024 * 1024 * 1024) * 1.05 " | bc ) 
# scale is for number of digits after the floating point

using awk

Size=$( awk -v ips="$IPS" -v dp="$DataPages" 'BEGIN{size=ips * dp/ (1024 * 1024 * 1024) * 1.05; printf "%0.02f",size}' )
sjsam
  • 20,774
  • 4
  • 49
  • 94