How to get block device name from partition device name?

I’m looking for a portable way to obtain parent block device name (e.g. /dev/sda) given the partition device name (e.g. /dev/sda1). I know I could just drop the last character, but that wouldn’t work in some cases:

  • MMC card readers typically have names like /dev/mmcblk0, while their partitions have names like /dev/mmcblk0p1 (notice the extra p).
  • optional: some block devices don’t have any partition table at all and are formatted as a single partition. In this case, partition device and parent block device are the same.

LVM volumes are a whole different kettle of fish. I don’t need to support them right now, but if taking them into account requires little extra effort, I wouldn’t mind.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you’re on linux you could use lsblk (which is part of util-linux):

lsblk -no pkname /dev/sda1

Method 2

If a device is a partition of another device then /sys/class/block/$dev will contain a file called partition (whose content is the partition number).

If that’s the case, you can get the name of the parent device with:

basename "$(readlink -f "/sys/class/block/$dev/..")"

Or with zsh:

echo /sys/class/block/$dev(:A:h:t)

Example:

$ dev=sda1
$ basename "$(readlink -f "/sys/class/block/$dev/..")"
sda
$ dev=nbd0p1
$ basename "$(readlink -f "/sys/class/block/$dev/..")"
nbd0

LVM volumes are completely different, they are not partitions except in the special case where they are one contiguous linear mapping of a physical PV.

If you’re in such a case, you can get the name of that PV with:

ls "/sys/class/block/$dev/slaves"

Where $dev is something like dm-2 (which you can obtain from "$(basename "$(readlink -f /dev/VG/LV)")").


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x