tags:

views:

41

answers:

1

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 reliable way to find the current number of partitions.

+1  A: 

What about:

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

?

caf
Thanks. That's more efficient solution.
baltusaj
Note that this while most UNIX-like operating systems support procfs, only Linux (afaik) supports non-process-related information (such as /proc/partitions). In other words, this is likely to fail on, for example, FreeBSD.
gamen
For some reason SO just told me "this comment may no longer be edited" when I edited my above post, so I'm adding this one instead. Daft.Additionally (Linux-specific too,) 'sdX' will only work on a reasonably modern system as older Linux kernels differentiate between drives using PATA or SCSI (as you might recall, PATA drives traditionally turned up as 'hdX').
gamen
Thanks gamen for the information. :)
baltusaj