提取分区数量的最佳方法是什么?

时间:2010-08-25 10:27:01

标签: linux bash

假设磁盘上只有主分区,找到当前分区数的最佳方法是什么?

有没有比这更好的方法:

fdisk -l > temp
#Following returns first column of the last line of temp e.g. /dev/sda4
lastPart=$(tail -n 1 temp | awk '{print $1}')
totalPartitions=$(echo ${lastPart:8})

$ totalPartitions 变量有时会返回 NULL 。这就是为什么,我想知道是否有更可靠的方法来查找当前的分区数。

3 个答案:

答案 0 :(得分:4)

怎么样:

totalPartitions=$(grep -c 'sda[0-9]' /proc/partitions)

答案 1 :(得分:1)

我在编写脚本以安全擦除测试并重新配置存储(有时是存储卡)时发现了这个问题,因此 mmcblk0p1 通常是其分区的格式。

这是我的答案:

diskICareAbout="sda"
totalPartitions="$( ls  /sys/block/${diskICareAbout}/*/partition  | wc -l )"

/proc/partitions 是陈旧而扁平的。 sys 文件系统可以很好地传达分区的层次结构特性,因此不需要 grep。

答案 2 :(得分:0)

您可以为此使用 partx。

-g

将返回分区总数(partx -rgo NR -n -1:-1 /dev/<disk> 省略标题行)。要获取磁盘上的最后一个分区,请使用

-r

如果分区编号存在间隙,这可能很有用。 -o 省略对齐空格,-n 指定要包含的逗号分隔列。 start:end 指定分区范围 -1,其中 suspendCoroutine 是最后一个分区。

相关问题