bash 如何检查磁盘的分区以在​​ Linux 中的脚本中使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26873289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:46:21  来源:igfitidea点击:

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

linuxbashdisk-partitioning

提问by Synthead

I'm scripting something in Bash for Linux systems. How would I check a disk for partitions in a robust manner?

我正在用 Bash 为 Linux 系统编写一些脚本。我将如何以稳健的方式检查磁盘的分区?

I could use grep, awk, or sedto parse the output from fdisk, sfdisk, etc., but this doesn't seem to be an exact science.

我可以使用grepawksed从解析输出fdisksfdisk等等,但是这似乎并没有成为一门精确的科学。

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?

你会推荐什么?

回答by Synthead

I think I figured out a reliable way. I accidentally learned some more features of partprobewhile 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 fdiskor 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.

一起使用,我可以在不更新内核的情况下扫描磁盘分区并获得可靠的输出来解析。它仍然解析文本,但至少输出不为“以人为本”为fdisksfdisk。这也是从磁盘读取的信息,并且不依赖于内核在该磁盘的分区状态上是最新的。

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

重要的是要注意,无论现有分区表或分区如何,每个退出状态都是 0。此外,我还注意到选项不能组合在一起(partprobe -d -s /dev/sdb有效而partprobe -ds /dev/sdb无效)。

回答by user3751385

Another option is to run:

另一种选择是运行:

lsblk

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

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