0

I am trying to multiply decimals and echo them

Here is what I have so far ...

#!/bin/bash

gbspace=1
limitUsers=2
limitInstances=2

echo $(($gbspace*0.5)) GB Webspace
echo limitUsers:$(($limitUsers*5))
echo limitUsers:$(($limitUsers*5)), limitInstances:$(($limitInstances)) \| Hi

and this is what I get ...

root@home /home/work # bash run
run: line 7: 1*0.5: syntax error: invalid arithmetic operator (error token is ".5")
limitUsers:10
limitUsers:10, limitInstances:2 | Hi
Vituvo
  • 1,008
  • 1
  • 9
  • 29
  • Bash does only integer arithmetic. You can either modify the logic to use integer arithmetic, or else use an external program to do your arithmetic. – AlexP Nov 14 '17 at 22:48
  • BTW, instead of multiplying by `0.5`, why don't you divide by `2`? – Charles Duffy Nov 14 '17 at 23:03

1 Answers1

2

Use bc which is pre-installed on most systems, with the -l flag to enable floating-point arithmetic:

echo $(echo "$gbspace*0.5" | bc -l) "GB Webspace"

Note that you have to be careful with the quoting, and you have to pipe the expression you want to compute to bc with the echo command.

Fabien Viger
  • 111
  • 4
  • 1
    Note the "Answer Well-Asked Questions" section in [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the reference to questions which *"have already been asked and answered many times before"*. – Charles Duffy Nov 14 '17 at 23:01
  • Fabien's answer was exactly what I needed. I did see those other threads beforehand but didn't understand how I could implement it correctly. Thanks. – Vituvo Nov 15 '17 at 21:38
  • @CharlesDuffy: will do. Thanks for the pointer and the reminder! – Fabien Viger Nov 16 '17 at 14:59