5

When I put a flash disk into a card reader and make an image with dd, I see the actual size of the disk, like 512483328 bytes in the following example:

1000944+0 records in
1000944+0 records out
512483328 bytes (512 MB) copied, 33.0091 s, 15.5 MB/s

Is it possible to get the same number without actually copying the data?

  • 2
    blockdev --getsize64 /dev/ice – frostschutz Jan 9 '14 at 12:39
13

Using sgdisk

You can use sgdisk to print detailled information:

sgdisk --print <device>

[…]
Disk /dev/sdb: 15691776 sectors, 7.5 GiB
Logical sector size: 512 bytes
[…]

When you multiply the number of sectors with the sector size you get the exact byte count that should match the output of dd.

Using /sys directly

You can also get those numbers directly from /sys:

Number of sectors: /sys/block/<device>/size
Sector size: /sys/block/<device>/queue/logical_block_size

Here's a way of calculating the size:

sectors=$(cat /sys/block/sdb/size)
bs=$(cat /sys/block/sdb/queue/logical_block_size)
echo $(( $sectors * $bs ))        --- OR ---        echo "$sectors * $bs" | bc

Using udisks

udisks outputs the information directly. It is reported as size:

udisks --show-info <device> | grep size

Using blockdev

blockdev --getsize64 <device>

From /proc/partitions

grep ' sdb$' /proc/partitions

(number expressed in kibibytes).

  • Both $(($sectors * $bs)) and $((sectors * bs)) are POSIX, the first one is more portable. Earlier versions of the POSIX spec made it unclear whether the second was POSIX or not. The behavior for the second is only specified if the variables contain literal constants, not things like (1+1) – Stéphane Chazelas Jan 9 '14 at 13:13
  • With all the additions of various methods, this is turning into an awesome canonical answer IMO. @Alex, I normally advice waiting at least a day or so before accepting an answer, but I certainly do not deny Marco the rep for this for writing the bulk of the answer. – a CVn Jan 9 '14 at 13:44
0

This is something I usually use:

% echo $((gb=$((mb=$((kb=1024))*kb))*kb))

For example:

% echo $((gb=$((mb=$((kb=1024))*kb))*kb))
1073741824
  • Why was this edited? I don't see much use for the echo - it's not the kind of thing I would use inline and a pointless output such as you demonstrate only makes clutter. Generally I stick that declaration in a script somewhere so when I want, for instance, to dd bs=$((3*mb)) or any number of other things then I know exactly what I'm getting. That's why I evaluate it with null - the echo makes no sense to me. By the way though, it would make a lot more sense to, say, echo $((3*mb)) after it's already declared - that's something do all of the time. – mikeserv Mar 4 '14 at 3:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.