How to get block device name from partition device name?

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)")").


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

lsblk -no pkname /dev/sda1