Linux: Script to Partition Disk

Objective: Automate the partitioning of a disk using a script on Linux.

There are primarily 3 common utilities to partition a disk on Linux. They are: fdisk, sfdisk and parted. We will cover all three of them in this article. cfdisk can also be used for disk partitioning, but it’s a curses based program and will not be covered here.

I created a small 128MB disk on a VM. Let’s say that I want to create 2 primary partitions of 64MB each using GPT partition table. Let’s see how we can script this.

First, let’s make sure that no partitions are defined in the new disk. In this example, we are going to use /dev/sdc for the new disk.

Partition Using fdisk

fdisk is able to read commands from stdin (standard input), so what we will need to do is to feed commands to fdisk to create the partitions.

The lines between FDISK_CMDS above are actual commands that would normally be typed on the fdisk prompt. It definitely looks cryptic. Below is a better version with comments.

For the command format above, sed will strip the comments before passing the commands to fdisk.

Let’s look at the partition table after running the above command. Two partitions are created under GPT.

Partition Using parted

To script the partition layout using parted, we can make use of the mklabel and mkpart commands.

Partition Using sfdisk

Lastly, we will script the disk partioning using sfdisk. sfdisk is a script-oriented tool for partitioning devices.

To use sfdisk, I find it easier to manually create the partition layout, dump the layout to a file, and then use the dump file to create partitions.

To dump the partitions of /dev/sdc, run sfdisk using --dump option.

Below is how the dump file looks like.

To partition the disk using the dump file, use the dump file as an input to sfdisk.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }