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
  • 3
    do you use bash (because of tag) or sh (first line of script)? – Romeo Ninov Jan 22 at 12:36
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.)

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.

-1

BC does it:

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.