Warm tip: This article is reproduced from serverfault.com, please click

Division does not work in bash

发布于 2021-01-13 22:46:00

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
Questioner
Kjellson
Viewed
0
Håkan Lindqvist 2019-01-22 19:58:16

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.)