I try to find the size of my disk, so i runned the below command
$ sudo fdisk -s /dev/sda
976762584
It shows like above. I think the size(976762584
) of the disk is shown in kilobytes. How do i convert the value to megabytes or gigabytes through terminal for better understanding?
numfmt
(part of GNU Coreutils) can be used here:The shell does fixed-width integer arithmetic with no check for overflow. So, when doing a calculation that might involve either large numbers or fractions,
bc
is a good choice. To get megabytes:To get gigabytes:
The assignment
scale=2
tellsbc
to display two decimal places.In awk
To find the size of the disk in Megabytes,
To find the size of the disk in Gigabytes,
There's a tool called units, which can be used for units conversion:
It is available as a package via
apt install units
.It is a fairly standard tool, that can be found installed by default on various other UNIX-like systems (e.g., FreeBSD). Keep in mind that units(1) syntax may differ across implementations available on various operating systems. Here's the same conversion but this time with FreeBSD units(1):
If the size is given in Kilobytes, you need to calculate through Bash built-in expressions. Assuming block size = 512B, you have to type:
This will show disk size in KiB. To go further, just add
/1024
to the end of expression:This will show disk size in MiB and so on.
You can do this natively with Bash and pseudo-floating point numbers. Define this function in your
~/.bashrc
and reopen your terminal:Now test it:
If you're using Bash or Zsh, this function will perform the calculation for you. Additionally, if
-si
is the first argument, calculations are performed in SI units.For example:
This is also compatible with e.g.
sort -h
.