Created
November 3, 2018 01:50
-
-
Save gnif/cadc611f04998706559def45318a0129 to your computer and use it in GitHub Desktop.
[BASH] Convert bytes to human readable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
bytesToHR 1 | |
bytesToHR 1023 | |
bytesToHR 1024 | |
bytesToHR 12345 | |
bytesToHR 123456 | |
bytesToHR 1234567 | |
bytesToHR 12345678 |
#!/usr/bin/env bash
function hr() {
local S="$1"
for U in B KiB MiB GiB TiB PiB EiB ZiB; do
test "$S" -lt 1024 && echo "$S$U" && break;
S="$((S/1024))"
done
}
Thanks however your version will truncate the result of each division, resulting in a less accurate result.
Maybe, but it doesn't seem to be an issue in practice:
$ hr $((1024*1024*1024*1024))
1TiB
$ hr $((1024*1024*1024*1024-1))
1023GiB
This seems right, though its reasonable if you'd prefer it to round up in this case.
Do you have a particular case in mind where it would be a mistake?
It doesn't replicate the original output with two decimal places of accuracy or aligned formatting.
That's true.
In my use case (printing out the approximate size of a directory in ci) I prefer fewer lines to formatted or highly precise output.
Thanks for sharing your original version btw, this was the best design I found that didn't use numfmt
which is missing from github windows runners.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script outputs: