Quantcast
Channel: A standard tool to convert a byte-count into human KiB MiB etc; like du, ls1 - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 21

Answer by Geoffrey for A standard tool to convert a byte-count into human KiB MiB etc; like du, ls1

$
0
0

Here is a way to do it almost purely in bash, just needs 'bc' for the floating point math.

function bytesToHR() {
        local SIZE=$1
        local UNITS="B KiB MiB GiB TiB PiB"
        for F in $UNITS; do
                local UNIT=$F
                test ${SIZE%.*} -lt 1024 && break;
                SIZE=$(echo "$SIZE / 1024" | bc -l)
        done

    if [ "$UNIT" == "B" ]; then
        printf "%4.0f    %s\n" $SIZE $UNIT
    else
        printf "%7.02f %s\n" $SIZE $UNIT
    fi
}

Usage:

bytesToHR 1
bytesToHR 1023
bytesToHR 1024
bytesToHR 12345
bytesToHR 123456
bytesToHR 1234567
bytesToHR 12345678

Output:

   1    B
1023    B
   1.00 KiB
  12.06 KiB
 120.56 KiB
   1.18 MiB
  11.77 MiB

Viewing all articles
Browse latest Browse all 21

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>