DEV Community

gunitinug
gunitinug

Posted on

2 1

Calculating total size of disks

This is the output of lsblk command on my Ubuntu machine:

$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0    7:0    0   1.7G  1 loop /snap/0ad/592
...
sda      8:0    0 111.8G  0 disk 
├─sda1   8:1    0   619M  0 part /boot/efi
├─sda2   8:2    0   954M  0 part [SWAP]
└─sda3   8:3    0 110.3G  0 part /home
sdb      8:16   0 931.5G  0 disk 
└─sdb1   8:17   0 931.5G  0 part /
sr0     11:0    1 383.5M  0 rom  
Enter fullscreen mode Exit fullscreen mode

I wanted to get total size of disks sda and sdb together, but I wanted to use bash to do it.

First, I only get lines beginning with sda or sdb:

$ lsblk | grep -Pi '^sda|^sdb'
sda      8:0    0 111.8G  0 disk 
sdb      8:16   0 931.5G  0 disk
Enter fullscreen mode Exit fullscreen mode

Then we isolate just the fourth column delimited by spaces (that is SIZE column).

$ lsblk | grep -Pi '^sda|^sdb' | awk '{print $4}'
111.8G
931.5G
Enter fullscreen mode Exit fullscreen mode

Next step would be to add 111.8G and 931.5G together. So we do that:

$ lsblk | grep -Pi '^sda|^sdb' | awk '{print $4}' | awk '{total+=$1} END {printf "%.1fG\n",total}'
1043.3G
Enter fullscreen mode Exit fullscreen mode

Lastly, let's convert the answer to terabytes (since the answer is in gigabytes):

logan@logan-mainPC:~$ lsblk | grep -Pi '^sda|^sdb' | awk '{print $4}' | awk '{total+=$1} END {printf "%.1fG\n",total}' | awk '{terabyte=$1/1000; printf "%.1fT\n",terabyte}'
1.0T
Enter fullscreen mode Exit fullscreen mode

So we conclude that 1043.3G is about 1T in size. Now we know that we would need at least 1T of space to copy the contents of both sda and sdb to another hard disk. :)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
thomasbnt profile image
Thomas Bnt

Oh cool command! Also thanks for your article, and welcome on DEV! 🙌

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay