Linux – Given a block device, how to detect if names of partitions must contain ā€œpā€

block-devicelinuxlinux-kernelpartition

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

Best Answer

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)