I'm scripting something in Bash for Linux systems. How would I check a disk for partitions in a robust manner?
I could use grep
, awk
, or sed
to parse the output from fdisk
, sfdisk
, etc., but this doesn't seem to be an exact science.
I could also check if there are partitions in /dev
, but it is also possible that the partitions exist and haven't been probed yet (via partprobe
, as an example).
What would you recommend?
I think I figured out a reliable way. I accidentally learned some more features of
partprobe
while reading the man page:Used together, I can scan a disk for partitions without updating the kernel and get a reliable output to parse. It's still parsing text, but at least the output isn't as "human-oriented" as
fdisk
orsfdisk
. This also is information as read from the disk and doesn't rely on the kernel being up-to-date on the partition status for this disk.Take a look:
On a disk with no partition table:
On a disk with a partition table but no partitions:
On a disk with a partition table and one partition:
On a disk with a partition table and multiple partitions:
It is important to note that every exit status was 0 regardless of an existing partition table or partitions. In addition, I also noticed that the options cannot be grouped together (
partprobe -d -s /dev/sdb
works whilepartprobe -ds /dev/sdb
does not).