Skip to content

Instantly share code, notes, and snippets.

@gnif
Created November 3, 2018 01:50
Show Gist options
  • Save gnif/cadc611f04998706559def45318a0129 to your computer and use it in GitHub Desktop.
Save gnif/cadc611f04998706559def45318a0129 to your computer and use it in GitHub Desktop.
[BASH] Convert bytes to human readable
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
@infogulch
Copy link

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?

@gnif
Copy link
Author

gnif commented Nov 16, 2023

It doesn't replicate the original output with two decimal places of accuracy or aligned formatting.

@infogulch
Copy link

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