3

I need to be able to determine the size of a block special file.

For example, given /dev/sda, I need a command that will provide the size of the device. (By size I mean capacity, since this is a storage device.)


Rationale:

I can store information in the device with:

echo "12345" >/dev/sda  # needs to be run as root

(Don't run that command by the way... unless you don't care about your data.)

However, I need to know how much data I can store on the device and I don't know how to do that.

Nathan Osman
  • 6,240

4 Answers4

5

blockdev provides a way to set/get block device attributes. To get the size in bytes:

blockdev --getsize64 /dev/sda

Alternatively, some info is available under /sys/block/<device> directory, e.g. cat /sys/block/sda/size gives the sda size measured in blocks of 512 bytes. See /sys/block/sda/sda1/size for sda1 partition size.

For sda size in KiB

echo $[  $(cat /sys/block/sda/size) / 2 ]

For sda size in Bytes

echo $[  $(cat /sys/block/sda/size) * 512 ]
forcefsck
  • 7,964
2

Parsing fdisk -l /dev/sda should give you exactly that:

Disk /dev/sda: 68.7 GB, 68719476736 bytes
255 heads, 63 sectors/track, 8354 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000bd83f

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1        8009    64325632   83  Linux
/dev/sda2            8009        8355     2780161    5  Extended
/dev/sda5            8009        8355     2780160   82  Linux swap / Solaris
1

I don't think there's a general, cross-platform answer. On Linux, the information is in /proc/partitions (in spite of the name, this contains all (most?) block devices, not just PC-style partitions).

awk '$4 == "sda" {print $3}' /proc/partitions
0

/proc/partitions has the data that you are looking for. This is where fdisk is going to get its data from.

For example in my system

major minor  #blocks  name
   8     0  976762584 sda
   8     1    8385898 sda1
   8     2  968374102 sda2
   8    16  976762584 sdb
   8    17    8385898 sdb1
   8    18  968374102 sdb2
   8    32  976762584 sdc
   8    33    8385898 sdc1
   8    34  968374102 sdc2
   8    48  976762584 sdd
   8    49    8385898 sdd1
   8    50  968374102 sdd2
   9     2 2905122048 md2
  • FWIW, I just looked at the fdisk source code. It calls the BLKGETSIZE ioctl, which returns bytes, then divides that result by 512. (As of 2017; maybe it's changed before or since.) – Edward Falk Oct 04 '19 at 23:07