How to automate fdisk (how to partition a lot of disks quickly)

Imagine you need to create say 10 disks with predefined partitions loaded with some software. The ideal solution would be automatic disk partitioning and copying the software to it. While copying files is an easy-to-do everyday procedure partitioning is a bit more tricky (really, just a little bit). Here is a quick trick that will allow you to partition disks quickly.


One way is using sfdisk. I don’t want to provide details for that program as there is manual for it: http://linux.die.net/man/8/sfdisk. However on some systems installing this program could be tricky. So let’s use standard fdisk for our task. We’ll learn its commands by heart and feed them to fdisk’s stdin like this:


01 echo "d
02 1
03 d
04 2
05 d
06 3
07 d
08 4
09 n
10 p
11 1
12
13 +10000M
14 n
15 p
16 2
17
18
19 a
20 1
21 w
22 " | fdisk /dev/sde

Lines 01-08 delete existing partitions if there are any. For fresh disks you should skip them. Just make sure you do not put newline between opening quote and the first command.

Lines 09-11 start creation of new primary partition #1

Line 12 is empty to accept proposed starting cylinder 1 for the new partition.

Line 13 sets the size of the first partition to 10000Mb (approximately 10 gig).

Lines 14-18 create primary partition #2 that occupies the rest of the disk.

Lines 19-20 mark partition 1 as active.

Line 21 writes the partition table to the disk. You might be interested in reading this post as well if you’re experiencing problems with writing the partition table to the disk.

Line 22 passes our commands to fdisk and tells it to partition /dev/hde. Replace it with whatever the name of your device is.

If you’re going to partition internal disks then just buy external enclosure and plug the disks via USB. This will speed up to process of swapping disks.

The proposed solution works for windows too if you decide to partition disks for windows on a Linux machine, which I think is a good solution.

Leave a Reply