Linux: Get capacity of a drive with fdisk (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 fdisk:

sudo fdisk -l <device> | grep -i 'disk /'

grep -i "disk /" is for English installations. In German it is a bit different because depending on the fdisk version the “disk” is called “Festplatte” or “Platte”:

sudo fdisk -l <device> | grep -i 'platte /'

<device> is the name of the device, e.g. /dev/sda

Now you can easily use this information in a batch script (works for English and German installations):

CAPACITY=`fdisk -l $DEVICE 2> /dev/null | grep -i 'platte /\|disk / ' | sed -r 's/.*\, (.*) byte.*/\1/I'`
echo "$DEVICE has a capacity of $CAPACITY bytes."

2> /dev/null avoids error lines like “no partiontable”.
The script has to be executed with root permissions because otherwise fdisk wouldn’t have access to the device.

Another good – if not better – method to retrieve the size of a disk drive can be found here: (no need for root permission, a bit easier to get)

Have a look at this post to find out how to avoid language hassles with command outputs.

Tagged with: , , , , ,

Leave a Reply

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