Linux: Get capacity of a drive with lsblk (NO root permission needed)

Sometimes one needs to know the exact capacity of a drive (e.g. for bash scripts).

Here is a one liner for this with lsblk which has the advantage that it doesn’t need root permission:

lsblk -b <device>

<device> is the name of the device, e.g. /dev/sda
-b parm is needed to get the exact capacity.

Now you can easily use this information in a batch script:

#!/bin/bash
DEVICE='/dev/sda'
CAPACITY=`lsblk -b -l -n -o SIZE $DEVICE | head -n 1`
echo "$DEVICE has a capacity of $CAPACITY bytes."

Notes:
-b is for getting the exact capacity in bytes instead of a human readable variant.
-l is for getting the list output format instead of the tree view.
-n is to suppress the headline.
-o SIZE tells lsblk to just give the size information.
head -n 1 is for getting only the size of the whole device instead of a list containing sizes of all partitions.

Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*