9

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Synthead
  • 2,162
  • 5
  • 22
  • 25
  • 2
    What are you trying to detect exactly? What is your ultimate goal? – Etan Reisner Nov 11 '14 at 19:54
  • 2
    `sfdisk -d` produces a format that is somewhat easier to parse, although still not ideal. `kpartx -l` is even better in that regard, if you have it installed. There may be other utilities as well. – twalberg Nov 11 '14 at 20:16
  • @Ethan Reisner: No catch; I'm merely just checking for partitions. If there aren't any, the script will eventually make a new MBR partition schema and create one large partition on the drive. – Synthead Nov 11 '14 at 20:26
  • `sfdisk` on RHEL 5.5 complains about GPT label. Asks me to use `parted` instead. – Felipe Alvarez Mar 21 '16 at 03:45

3 Answers3

13

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

Synthead
  • 2,162
  • 5
  • 22
  • 25
0

Another option is to run:

lsblk

See https://unix.stackexchange.com/a/108951

Community
  • 1
  • 1
user3751385
  • 3,752
  • 2
  • 24
  • 24
0

you could also use:

parted /dev/sda print 1 &> /dev/null echo $?

if a partition (first partition) exist it return true and otherwise false

Hamid Reza Moradi
  • 429
  • 2
  • 4
  • 11