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
How to check a disk for partitions for use in a script in Linux?
提问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 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?
你会推荐什么?
回答by Synthead
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
. 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.
一起使用,我可以在不更新内核的情况下扫描磁盘分区并获得可靠的输出来解析。它仍然解析文本,但至少输出不为“以人为本”为fdisk
或sfdisk
。这也是从磁盘读取的信息,并且不依赖于内核在该磁盘的分区状态上是最新的。
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).
重要的是要注意,无论现有分区表或分区如何,每个退出状态都是 0。此外,我还注意到选项不能组合在一起(partprobe -d -s /dev/sdb
有效而partprobe -ds /dev/sdb
无效)。