Skip to content

Instantly share code, notes, and snippets.

@jamesstout
Last active September 15, 2021 23:15
Show Gist options
  • Save jamesstout/6165581 to your computer and use it in GitHub Desktop.
Save jamesstout/6165581 to your computer and use it in GitHub Desktop.
Takes the output from du -k - file block count in 1024-byte (1-Kbyte) blocks and converts to a human readable form.
# $1 = file block count in 1024-byte (1-Kbyte) blocks.
# i.e. output from du -k
# no floating points, just ints, but check anyway
function convertToHuman {
size=$(echo $1 | sed -e 's/^\./0./') # add 0 for cases like ".0001"
size=${size/\.*} # convert to int
for unit in KB MB GB TB PB EB ZB YB; do
if [ "$size" -lt 1024 ]; then
echo "${size} ${unit}";
break;
fi;
size=$((size+512)); # to round to nearest you add (denom/2) to the numerator
size=$((size/1024));
done;
}
function printReport {
local startSize="${1:-0}"
local endSize="${2:-0}"
local savings=$(echo "(1 - ($endSize / $startSize)) * 100" | bc -l | sed -e 's/^\./0./' )
# if the file size is over ~100 MB, start using the human output
if [ "$startSize" -gt 100000 ]; then
startSize=$(convertToHuman "$startSize")
endSize=$(convertToHuman "$endSize")
else
startSize=$(printf "%'d KB" "$startSize")
endSize=$(printf "%'d KB" "$endSize")
fi
if [ ${savings/\.*} -gt 0 ]; then
printf "Optimised %s to %s (saving %2.2f%%)\n" "$startSize" "$endSize" "$savings"
else
printf "No savings. Start: %s End: %s\n" "$startSize" "$endSize"
fi
}
#### NOTES
printf "%'d" "$NUMBER" 2> /dev/null
# prints out integers with thousand separators. The dev/null redirect is to handle floats.
# e.g.
# printf "%'d" 1034343.56 2> /dev/null
# 1,034,343
# printf "%'d" 1034 2> /dev/null
# 1,034
@jamesstout
Copy link
Author

Takes the output from du -k - file block count in 1024-byte (1-Kbyte) blocks and converts to a human readable form. e.g.

james@Jamess-iMac: ~/Projects/Github 
$ du -sk 
2141672 . 
$ convertToHuman 2141672 
2 GB 

Main issue - It rounds down as bash maths is integer only. Still it's a start ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment