Last active
June 4, 2022 15:22
-
-
Save Rendevior/27bd2c39e54ac3c83ba3674f85bcbe33 to your computer and use it in GitHub Desktop.
Byte Unit Conversion with Decimal in Bash
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
#!/bin/sh | |
unit_conversion(){ | |
B="${1}" | |
KB="$(awk -v "p=${B}" 'BEGIN{ p=p / 1024; printf "%0.2f", p}')" | |
MB="$(awk -v "p=${KB}" 'BEGIN{ p=p / 1024; printf "%0.2f", p}')" | |
GB="$(awk -v "p=${MB}" 'BEGIN{ p=p / 1024; printf "%0.2f", p}')" | |
TB="$(awk -v "p=${GB}" 'BEGIN{ p=p / 1024; printf "%0.2f", p}')" | |
[ "${TB%%.*}" -gt "0" ] && printf '%s %s\n' "${TB}" "TB" && return 0 | |
[ "${GB%%.*}" -gt "0" ] && printf '%s %s\n' "${GB}" "GB" && return 0 | |
[ "${MB%%.*}" -gt "0" ] && printf '%s %s\n' "${MB}" "MB" && return 0 | |
[ "${KB%%.*}" -gt "0" ] && printf '%s %s\n' "${KB}" "KB" && return 0 | |
[ "${B%%.*}" -gt "0" ] && printf '%s %s\n' "${B}" "B" | |
} | |
unit_conversion "$1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
root@OK:~#
unit_conversion "372637383"
Output:
355.37 MB