How to Automate Disk Partitioning Using the sfdisk Command in Linux

When you are architecting a massive automated server deployment pipeline, manually configuring disk partitions using interactive tools like fdisk or cfdisk is a mathematical failure. These tools require real-time human keystrokes, which completely breaks automation scripts. To force the Linux kernel to violently restructure a physical hard drive based on a pre-defined, algorithmic script, you must use the highly advanced sfdisk command.

Understanding the Scripted Architecture

The sfdisk (Scriptable fdisk) command is a deeply powerful, non-interactive partition table manipulator. It does not launch a graphical UI or a command shell; it strictly ingests standard input strings (or a text file) and instantly executes the geometric calculations, rewriting the partition table (MBR or GPT) in milliseconds without any human confirmation.

CRITICAL INFRASTRUCTURE WARNING: The sfdisk command is mathematically ruthless. Because it requires zero human confirmation, a single typo in your deployment script will instantly and irreversibly obliterate the partition table of the target drive. You must deploy absolute root privileges to execute this command.

Executing the Automated Partition Injection

Imagine you have a raw, blank NVMe drive attached as /dev/sdb. You want to instantly write a script that creates two partitions: a 50GB boot partition and a massive secondary partition using all remaining space.

Instead of typing commands, you can inject the mathematical geometry directly into the engine using standard input.

Open your terminal and type the following multi-line execution block:

sudo sfdisk /dev/sdb << EOF
size=50G, type=L
size=+, type=L
EOF

The exact millisecond the EOF (End of File) tag is processed, the sfdisk engine violently rips open the partition table on /dev/sdb, calculates the exact sector boundaries, and writes the two new Linux partitions (type L). It is flawlessly automated.

Cloning Partition Architectures

You can also use sfdisk to execute a perfect mathematical clone of a partition table from one drive to another, which is critical for configuring RAID arrays.

To clone the architecture of /dev/sda directly onto /dev/sdb, execute:

sudo sfdisk -d /dev/sda | sudo sfdisk /dev/sdb

This command dynamically dumps the geometric matrix of sda and pipes it directly into the execution engine of sdb.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.