Shell Script – How to Get Block Device Name from Partition Device Name

block-devicepartitionshell-script

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.

Best Answer

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

lsblk -no pkname /dev/sda1