Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a disk for partitions for use in a script in Linux?

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?

like image 886
Synthead Avatar asked Nov 11 '14 19:11

Synthead


1 Answers

I think I figured out a reliable way. I accidentally learned some more features of partprobe while reading the man page:

-d     Don’t update the kernel.
-s     Show a summary of devices and their partitions.

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 or sfdisk. 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:

# partprobe -d -s /dev/sdb
(no output)

On a disk with a partition table but no partitions:

# partprobe -d -s /dev/sdb
/dev/sdb: msdos partitions

On a disk with a partition table and one partition:

# partprobe -d -s /dev/sdb
/dev/sdb: msdos partitions 1

On a disk with a partition table and multiple partitions:

# partprobe -d -s /dev/sda
/dev/sda: msdos partitions 1 2 3 4 <5 6 7>

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 while partprobe -ds /dev/sdb does not).

like image 119
Synthead Avatar answered Oct 25 '22 05:10

Synthead