Skip to content

Instantly share code, notes, and snippets.

@Rendevior
Last active June 4, 2022 15:22
Show Gist options
  • Save Rendevior/27bd2c39e54ac3c83ba3674f85bcbe33 to your computer and use it in GitHub Desktop.
Save Rendevior/27bd2c39e54ac3c83ba3674f85bcbe33 to your computer and use it in GitHub Desktop.
Byte Unit Conversion with Decimal in Bash
#!/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"
@Rendevior
Copy link
Author

Rendevior commented Nov 18, 2021

root@OK:~# unit_conversion "372637383"
Output:
355.37 MB

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