4

I want to automatically partition a block device with sfdisk. This might be an SD card, a hard disk, SATA or NVME device. Initially I thought that sfdisk requires these names and thus I was looking to generate them correctly but apparently one can leave them out anyway. :)

Unlike the traditional ATA and SATA devices that have partitions names simply appended to the device name (e.g., /dev/sda1 for the first partition of block device sda) there exists another scheme for block devices that are flash-based and use other drivers. These add a p between the device and partition name (e.g. /dev/mmcblk0p1 for the first partition of mmcblk0). Unfortunately I have not found any kernel documentation on these details.

Given a block device (e.g., /dev/mmcblk0) how do I decide if the respective (yet non-existing) partitions will be named with an p or not (e.g., /dev/mmcblk0p1 or /dev/mmcblk01)?

This is basically the reverse question of this one but with the additional twist, that the partitions do not exist yet (for the sake of this question I do not allow the answer to actually modify the partition table thus trying it out is not valid).

2 Answers 2

11

If device name ends with digit then kernel adds 'p' symbol to separate partition number from device name.

/dev/sda -> /dev/sda1
/dev/mmcblk0 -> /dev/mmcblk0p1

For details see disk_name function in Linux kernel sources (linux/block/partition-generic.c):

if (isdigit(hd->disk_name[strlen(hd->disk_name)-1]))
    snprintf(buf, BDEVNAME_SIZE, "%sp%d", hd->disk_name, partno);
else
    snprintf(buf, BDEVNAME_SIZE, "%s%d", hd->disk_name, partno)
0
0

Here is what might or might not be helpful in this endeavor:

# Try to figure out if partition names are separated by "p" from the device name or not.
# The following cases imply a "p"
# - If the device name starts with mmcblk (common drivers for SD card readers)
# - If there is no device/type file for the respective device in /sys/class/block (e.g., NVME drives)
# - If the respective device/type indicates "0" (hard disks)
base_dev=$(basename "$sd_dev")
if [[ "$base_dev" =~ mmcblk[0-9]+ || \
      ! -e "/sys/class/block/${base_dev}/device/type" || \
      $(cat "/sys/class/block/${base_dev}/device/type") != 0 \
    ]]; then
    part_sep="p"
else
    part_sep=""
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .