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 /'
Note:
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):
#!/bin/bash DEVICE='/dev/sda' 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."
Notes:
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: https://www.nerd-quickies.net/2015/09/16/linux-get-capacity-of-a-drive-with-lsblk-no-root-permission-needed/ (no need for root permission, a bit easier to get)
UPDATE:
Have a look at this post to find out how to avoid language hassles with command outputs.
Leave a Reply