How to Use fdisk Command in Linux: Syntax and Examples
The
fdisk command in Linux is used to create, delete, and manage disk partitions interactively. Run sudo fdisk /dev/sdX (replace /dev/sdX with your disk) to enter the fdisk menu where you can use commands like n to create a new partition and w to save changes.Syntax
The basic syntax of the fdisk command is:
sudo fdisk [options] device
Here:
sudoruns the command with administrator rights needed for disk changes.fdiskis the command itself.deviceis the disk you want to manage, like/dev/sdaor/dev/sdb.
Inside the interactive menu, you use single-letter commands like m for help, p to print the partition table, n to add a new partition, and w to write changes.
bash
sudo fdisk /dev/sdX
Example
This example shows how to create a new partition on disk /dev/sdb using fdisk. It demonstrates entering fdisk, listing partitions, creating a new one, and saving changes.
bash
sudo fdisk /dev/sdb # Inside fdisk interactive prompt: # Command (m for help): p # (prints current partitions) # Command (m for help): n # Partition type # p primary (0 primary, 0 extended, 4 free) # e extended # Select (default p): p # Partition number (1-4, default 1): 1 # First sector (2048-..., default 2048): (press Enter) # Last sector, +sectors or +size{K,M,G,T,P} (2048-..., default ...): +1G # Command (m for help): w # (writes changes and exits)
Output
Disk /dev/sdb: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x12345678
Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 2099199 2097152 1G 83 Linux
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.
Common Pitfalls
Common mistakes when using fdisk include:
- Not running
fdiskwithsudo, causing permission errors. - Choosing the wrong disk device, which can lead to data loss.
- Forgetting to write changes with
w, so no changes are saved. - Not backing up data before modifying partitions.
Always double-check the disk device and backup important data before using fdisk.
bash
sudo fdisk /dev/sda # User forgets to type 'w' and exits with 'q' # No changes are saved # Correct way: # After making changes, type 'w' to save and exit
Quick Reference
| Command | Description |
|---|---|
| m | Show help menu with all commands |
| p | Print current partition table |
| n | Create a new partition |
| d | Delete a partition |
| t | Change a partition's type |
| w | Write changes to disk and exit |
| q | Quit without saving changes |
Key Takeaways
Always run fdisk with sudo to have the necessary permissions.
Use fdisk interactively to create, delete, or modify disk partitions safely.
Double-check the disk device name before making changes to avoid data loss.
Remember to write changes with the 'w' command to apply them.
Back up important data before modifying partitions with fdisk.