Bash – Convert KB To MB using Bash

bashshell

I use a command to get the size of a remote folder, after it's run it returns

120928312 http://blah.com

The number is size in bytes. What I'd like to do is have it output in MB, and the http part removed. I'm guessing greping to a file but not sure how to go about it.

Best Answer

You can do it with shell builtins

some_command | while read KB dummy;do echo $((KB/1024))MB;done

Here is a more useful version:

#!/bin/sh
human_print(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} bytes && break
  KB=$(((B+512)/1024))
  [ $KB -lt 1024 ] && echo ${KB} kilobytes && break
  MB=$(((KB+512)/1024))
  [ $MB -lt 1024 ] && echo ${MB} megabytes && break
  GB=$(((MB+512)/1024))
  [ $GB -lt 1024 ] && echo ${GB} gigabytes && break
  echo $(((GB+512)/1024)) terabytes
done
}

echo 120928312 http://blah.com | human_print