When you plug a brand new hard drive into a Linux server, or if you need to completely repurpose an old USB flash drive, the operating system cannot use it immediately. Before a filesystem can be created, the raw disk must be divided into logical sections called partitions. The traditional, robust, and universally available tool for creating, deleting, and modifying these disk partitions in the Linux terminal is the fdisk (format disk) command.
Warning: Modifying disk partitions is dangerous. Using fdisk incorrectly will instantly and permanently destroy all data on the target drive. Always ensure you have selected the correct disk before proceeding.
Identifying the Correct Drive
Before you can format a partition, you must know the exact device name assigned to your drive by the Linux kernel.
- Open your terminal and run the command with the
-l(list) flag as the root user:sudo fdisk -l - This will output a list of every storage device attached to the system. Look for your target drive based on its size (e.g., 500GB, 1TB).
- Note the device name. The primary hard drive is usually
/dev/sda, a secondary drive might be/dev/sdb, and NVMe drives look like/dev/nvme0n1.
Entering the Interactive fdisk Menu
Once you have identified your target drive (for this example, we will assume the drive is /dev/sdb), you must launch fdisk in interactive mode targeting that specific device.
sudo fdisk /dev/sdb
You will be greeted by a prompt that says Command (m for help):. You are now inside the fdisk utility.
Creating a New Partition
To create a new, single partition that spans the entire disk:
- If the disk has old data on it, you can delete existing partitions by typing d and pressing Enter.
- To create a new partition, type n and press Enter.
- You will be asked if you want a primary or extended partition. Type p for primary and press Enter.
- When asked for the partition number, press Enter to accept the default (usually 1).
- When asked for the “First sector,” press Enter to accept the default (starting at the very beginning of the drive).
- When asked for the “Last sector,” press Enter to accept the default (ending at the absolute end of the drive, utilizing 100% of the available space).
- You have now laid out the partition scheme in memory. To permanently write these changes to the disk, type w and press Enter.
fdiskwill write the partition table and exit automatically.
Formatting the Partition (Creating the Filesystem)
fdisk only creates the physical boundary of the partition; it does not format it with a filesystem. If you try to mount the drive now, it will fail.
To format the newly created partition (which is now called /dev/sdb1, adding the ‘1’ to indicate the first partition on drive ‘b’) with the standard ext4 Linux filesystem, run:
sudo mkfs.ext4 /dev/sdb1
Once the formatting process reaches 100%, the drive is fully prepared and ready to be mounted and used by the operating system.