Skip to content

Instantly share code, notes, and snippets.

@gnif
Created November 3, 2018 01:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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
@gnif
Copy link
Author

gnif commented Nov 3, 2018

This script outputs:

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

@infogulch
Copy link

#!/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
}

@gnif
Copy link
Author

gnif commented Nov 16, 2023

Thanks however your version will truncate the result of each division, resulting in a less accurate result.

@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