简体   繁体   中英

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?

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

Another option is to run:

lsblk

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM