fdisk Command Cheat Sheet
fdisk is a menu-driven command-line utility for creating and manipulating partition tables on a hard disk. It understands GPT, MBR, Sun, SGI, and BSD partition tables.
Synopsis
fdisk [options] device
fdisk -l [device...]
Basic Usage
List Partitions (-l)
List the partition tables of specific devices or all devices if none given.
sudo fdisk -l
Start Interactive Mode
Open a disk for editing.
sudo fdisk /dev/sdX
sdX with your drive, e.g., /dev/sdb. Do not use partition numbers like sdb1 unless resizing loop devices).
Interactive commands
Once inside fdisk, you use single-letter commands.
| Command | Description |
|---|---|
m |
Display help menu |
p |
Print the partition table |
n |
Create a new partition |
d |
Delete a partition |
t |
Change partition type |
l |
List known partition types |
w |
Write changes to disk and exit |
q |
Quit without saving changes |
g |
Create a new empty GPT partition table |
o |
Create a new empty DOS (MBR) partition table |
v |
Verify the partition table |
Common Tasks
1. Create a New Partition
- Run
sudo fdisk /dev/sdb - Type
n(New) - Select partition type (Primary
por Extendede) - MBR only - Partition number (1-4)
- First sector (Press Enter for default)
- Last sector (Enter
+size, e.g.,+20Gfor 20GB) - Type
wto write changes.
2. Delete a Partition
- Type
d - Enter partition number (if multiple exist)
- Type
wto save.
3. Change Partition Type (e.g., to Swap or LVM)
- Type
t - Enter partition number
- Enter hex code (Type
Lto see codes)82: Linux Swap83: Linux (default)8e: Linux LVMef: EFI System (GPT)
- Type
wto save.
Scripting (Non-Interactive)
You can script fdisk by piping commands into it.
Create a Single Partition
echo -e "n\np\n1\n\n\nw" | sudo fdisk /dev/sdb
Create a Specific Size Partition
# New partition of 5GB
sed -e 's/\s*\([\+0-9a-zA-Z]*\).*/\1/' << EOF | sudo fdisk /dev/sdb
n
p
1
+5G
w
EOF
Better Alternative: sfdisk
For scripting, sfdisk is generally preferred over hacking fdisk with echo.
echo ",,L" | sudo sfdisk /dev/sdb
MBR vs GPT
- MBR (Master Boot Record): Legacy. Max 4 primary partitions (or 3 primary + 1 extended). Max 2TB disk size.
- GPT (GUID Partition Table): Modern. Limitless partitions (128 by default). Supports disks > 2TB.
Convert to GPT:
Inside fdisk, type g. Warning: This erases all data on the disk!
After Partitioning
Changes to the partition table are not always instantly visible to the kernel.
Reload Partition Table
sudo partprobe /dev/sdb
# OR
sudo kpartx -u /dev/sdb
Format the Partition
Once created, you must format it with a filesystem.
sudo mkfs.ext4 /dev/sdb1
Tips
- Safety: Double-check the device name (
lsblk) before openingfdisk. - Align: Modern
fdiskautomatically aligns partitions to physical sector boundaries (2048 sectors), which is crucial for SSD/RAID performance. - Resize:
fdiskcan resize partitions by deleting and recreating them with the SAME start sector and a larger end sector. (Risky, usegpartedorresize2fsif possible).