Skip to content

Instantly share code, notes, and snippets.

@agunnerson-ibm
Last active May 22, 2024 07:27
Show Gist options
  • Save agunnerson-ibm/efca449565a3e7356906 to your computer and use it in GitHub Desktop.
Save agunnerson-ibm/efca449565a3e7356906 to your computer and use it in GitHub Desktop.
Bash function to convert bytes to human readable size
# Copyright 2015 Andrew Gunnerson <andrewgunnerson@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Convert bytes to human readable size
# $1: Size in bytes
# $2: Floating point precision (digits after dot)
# Return: Nothing
# Prints: Human readable size
#
# Example: "$(human_readable 6390759424 2)" == "5.95 GiB"
human_readable() {
local abbrevs=(
$((1 << 60)):ZiB
$((1 << 50)):EiB
$((1 << 40)):TiB
$((1 << 30)):GiB
$((1 << 20)):MiB
$((1 << 10)):KiB
$((1)):bytes
)
local bytes="${1}"
local precision="${2}"
if [[ "${bytes}" == "1" ]]; then
echo "1 byte"
else
for item in "${abbrevs[@]}"; do
local factor="${item%:*}"
local abbrev="${item#*:}"
if [[ "${bytes}" -ge "${factor}" ]]; then
local size="$(bc -l <<< "${bytes} / ${factor}")"
printf "%.*f %s\n" "${precision}" "${size}" "${abbrev}"
break
fi
done
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment