Seb
Seb

Reputation: 43

Find the partition separator for a given Linux block device

I'm writing a script that will partition several disks on a Linux system. These disks can be all sorts of block devices. I need to find a way to reliably create the names of the partitions that will be created before I have created them. In other words, I need to know the character or string that will separate the disk's device name from the partition number when the partitions have been created.

Is there a file in the /sys/block tree that I can find from the root devices' node that contains this information?

I currently check if the root device' name contains nvme or mmcblk, in which case I use p as the separator. Otherwise I use the empty string.

But this seems fragile and likely incomplete.

Upvotes: 2

Views: 67

Answers (1)

Mike Andrews
Mike Andrews

Reputation: 3206

To directly answer your question, the code for assigning the device name for a partition is in the Linux kernel, in add_partition in block/partitions/core.c: https://github.com/torvalds/linux/blob/88fac17500f4ea49c7bac136cf1b27e7b9980075/block/partitions/core.c#L330

if (isdigit(dname[strlen(dname) - 1]))
    dev_set_name(pdev, "%sp%d", dname, partno);
else
    dev_set_name(pdev, "%s%d", dname, partno);

It's pretty simple. If the base device ends in a digit, there's a "p" between it and the partition index. Otherwise, there's no "p".

As an alternative to this approach, consider instead writing a udev rule that would create an entry in /dev/disk/by-uuid or by-id. This would give you something you can explicitly look up once the new partition device entry pops up.

Upvotes: 1

Related Questions