Skip to main content

Bash function to convert bytes into human readable format.

#
# Converts bytes to human readable format (ex: convert_bytes 2147483648 >>> 2.0G)
# https://github.com/andreafabrizi/Dropbox-Uploader/blob/master/dropbox_uploader.sh#L210
convert_bytes() {
    if [ -z "$1" ]; then
        echo "Usage: convert_bytes <bytes>"
        echo
        echo "Example:"
        echo
        echo "    Converts bytes to human a readable format."
        echo
        echo "    $ convert_bytes 2147483648"
        echo "    2.0G"
        return 1
    fi

    if [[ "$1" != "" ]]; then
        if (($1 > 1073741824));then
            echo $(($1/1073741824)).$(($1%1073741824/100000000))"G";
        elif (($1 > 1048576));then
            echo $(($1/1048576)).$(($1%1048576/100000))"M";
        elif (($1 > 1024));then
            echo $(($1/1024)).$(($1%1024/100))"K";
        else
            echo $1;
        fi
    else
        echo $1;
    fi
}