Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

division math in a bash script without bc?

Tags:

bash

I have a bash script where I need to calculate a percentage. For instance, I'll have two numbers (11 and 531, lets say) and the ideal would be do calculate 11/531*100 ~= 2

I don't need decimal values, in fact I'd like to truncate and thereby round down to the nearest whole number. It seems that to do floating point math I need to call out to bc or other utilities-- is there another way to accomplish what I'm looking for?

I don't have anything against bc but when I use it in my script, and configure the script as a nagios plugin then nagios appears for some unknown reason to refuse to proceed. It's very odd and annoying and before digging in too much more I wondered if I could avoid bc altogether in this situation.

like image 570
jkj2000 Avatar asked Sep 11 '25 19:09

jkj2000


2 Answers

use bash's math builtin. it just prints out the integers/whole numbers. so if you want to discard/truncate the decimal places use something like:

echo $(((11*100)/531)) # prints 2
like image 116
Marc Bredt Avatar answered Sep 13 '25 11:09

Marc Bredt


Try Awk - To get Floating point numbers as well

Eg:

NUM=44; awk -v NUM=$NUM 'BEGIN { print  ((NUM - 20) / 45) }'
like image 38
Debaditya Avatar answered Sep 13 '25 11:09

Debaditya