开发者

Best way to extract number of partitions?

Assuming that there are only primary partitions on a disk, what is the best way to find the current number of partitions?

Is there any better way than:

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 variable sometimes returns NULL. That's why, I was wondering if there is a more r开发者_如何学编程eliable way to find the current number of partitions.


What about:

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

?

(Where sda is the name of the disk you're interested in, replacing it as appropriate)


I found this question while I was writing a script to safely wipe test and re-provision storage, which is sometimes a memory card, so mmcblk0p1 is often the format of its partitions.

Here's my answer:

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

/proc/partitions is archaic and flat. The sys filesystem can comunicate the heirarchal nature of partitions well enough that grep is not needed.


You can use partx for this.

partx -g /dev/<disk> | wc -l

will return the total number of partitions (-g omits the header line). To get the last partition on a disk, use

partx -rgo NR -n -1:-1 /dev/<disk>

which may be useful if there are gaps in the partition numbers. -r omits aligning spaces, and -o specifies the comma-separated columns to include. -n specifies a range of partitions start:end, where -1 is the last partition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜