[英]How to check a disk for partitions for use in a script in Linux?
I'm scripting something in Bash for Linux systems. 我正在为Bash for Linux系统编写脚本。 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. 我可以使用
grep
, awk
或sed
来解析fdisk
, sfdisk
等的输出,但这似乎不是一门精确的科学。
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). 我还可以检查
/dev
是否存在分区,但是分区也可能存在并且尚未被探测(作为示例,通过partprobe
)。
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: 在阅读手册页时,我偶然学到了
partprobe
更多功能:
-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
. 它仍在解析文本,但至少输出不像
fdisk
或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. 重要的是要注意,无论现有分区表或分区如何,每个退出状态都为0。 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). 另外,我还注意到这些选项不能组合在一起(
partprobe -d -s /dev/sdb
有效,而partprobe -ds /dev/sdb
则没有)。
Another option is to run: 另一种选择是运行:
lsblk
See https://unix.stackexchange.com/a/108951 请参阅https://unix.stackexchange.com/a/108951
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.