3

I'd like to calculate some information from a file but division does not work. If I change the / to a + or -, this calculation it doing right. Any ideas?

#!/bin/sh
    FILE=/tmp/stats

    for EMPTY in $(cat $FILE |sed '1!d'); do (echo "Empty Servers $EMPTY | Empty-Servers=$EMPTY;"); done
    for SERVERS in $(cat $FILE |sed '2!d'); do (echo "Total Servers $SERVERS | Total=$SERVERS;"); done

    PERCENT=$(((EMPTY / SERVERS)*100))
    echo $PERCENT
1
  • 3
    do you use bash (because of tag) or sh (first line of script)? Jan 22, 2019 at 12:36

3 Answers 3

6

Division does work, only that what the shell only deals with integers.

I think you'll either want to invoke something like bc, then you can do math however you like, or adapt to the implications of dealing with integers.

Example of what you could do instead: change your expression around such that you multiply EMPTY by 100 first, then divide by SERVERS. Ie, $(((EMPTY * 100) / SERVERS)).
(Of course, this may not be as precise as you would like, but it does not yield 0 as the result all the time.)

0
1

According to this link, You need a $ before (EMPTY / SERVERS) too. So your script should be as below:

#!/bin/sh
FILE=/tmp/stats

for EMPTY in $(cat $FILE |sed '1!d'); do (echo "Empty Servers $EMPTY | Empty-Servers=$EMPTY;"); done
for SERVERS in $(cat $FILE |sed '2!d'); do (echo "Total Servers $SERVERS | Total=$SERVERS;"); done

PERCENT=$(($((EMPTY / SERVERS))*100))
echo $PERCENT

And according to this link, shell parsing is useful only for integer division so it's better to use bc.

0
-1

BC does it:

for PERCENT in $(echo "scale=3; ($EMPTY/$SERVERS)*100" | bc); do (echo "Percent Empty=$PERCENT;;");done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .