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. :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
thomasbnt profile image
Thomas Bnt

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay