How do I check disk for partitions for use in a script in Linux?
I am using a Bash script for Linux systems. How can I check the disk for partitions in a reliable way?
I could use grep
, awk
or sed
to parse the output from fdisk
, sfdisk
etc., but that doesn't seem to be the exact science.
I could also check if there are sections in /dev
, but it is also possible that sections exist and have not been explored yet (use as an example partprobe
).
What would you recommend?
source to share
I think I figured out a safe way. I learned a few more functions by accident 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 the disk for partitions without updating the kernel, and get reliable output for parsing. It still parses the text, but at least the output is not "human-oriented" like fdisk
or sfdisk
. It is also information read from the disk and does not rely on the kernel being up to date for the partition state for that disk.
Take a look:
On a disk without a 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 several partitions:
# partprobe -d -s /dev/sda
/dev/sda: msdos partitions 1 2 3 4 <5 6 7>
It is important to note that each exit status is 0 regardless of the existing partition table or partitions. Also, I also noticed that the options cannot be grouped together ( partprobe -d -s /dev/sdb
works, partprobe -ds /dev/sdb
doesn't).
source to share