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 |
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
It doesn't replicate the original output with two decimal places of accuracy or aligned formatting.