Search code examples
linuxfileunixsizedisk

How does the df command calculate "used space" in percentage?


Here's the output of

$df -k /
Filesystem     1kB-blocks     Used Available Use% Mounted on
/dev/sda2       470306374 94552036 351788872  22% /

Shouldn't it be (Used / Available) * 100? But the result I get is 26.8% instead of 22% in my system.


Solution

  • No, the free percentage would be (100 * used / total), not divided by available. Available is the free space left, not the total space.

    The source code for df, part of the coreutils package, is freely available. The calculations there are(1):

    uintmax_t u100 = v->used * 100;
    uintmax_t nonroot_total = v->used + v->available;
    pct = u100 / nonroot_total + (u100 % nonroot_total != 0);
    

    You can see from that second line that the denominator is the sum of used and available.

    In other words, its:

           94,552,036             94,552,036
    ------------------------  =  -----------  =  0.2118  -> 21% as integer
    94,552,036 + 351,788,872     446,340,908
    

    Rounding up (which is sensible for used space) is done in the third line of that code snippet, where it adds one unless a hundred times the used space is an exact multiple of the total.


    (1) There are actually other code paths that may be followed in the event integer calculations aren't suitable (they use floating point instead) but they all boil down to the same operations.