Skip to content

Latest commit

 

History

History
1249 lines (955 loc) · 20.5 KB

fdisk.md

File metadata and controls

1249 lines (955 loc) · 20.5 KB
title fdisk - Partition Table Manipulator
description Complete guide to fdisk - Partition Table Manipulator
category Storage
tags
storage
disk management
lvm
partitioning
systemd
difficulty beginner
last_updated 2026-06-06
related_commands
sfdisk
cfdisk
gdisk/sgdisk
parted
partprobe

fdisk - Partition Table Manipulator

Overview

fdisk is a dialog-driven program for creation and manipulation of partition tables. It understands GPT, MBR, Sun, SGI, and BSD partition tables. fdisk is a powerful tool for managing disk partitions on Linux systems and supports both interactive and scripted operations.

Installation

Package Managers

# Debian/Ubuntu (part of util-linux)
apt-get install util-linux

# RHEL/CentOS/Fedora
dnf install util-linux

# Arch Linux
pacman -S util-linux

# Alpine Linux
apk add util-linux

Basic Syntax

fdisk [OPTIONS] DEVICE
fdisk -l [DEVICE...]

Command Structure

Interactive Mode

# Enter interactive mode for a device
fdisk /dev/sda

# Common interactive commands:
# m - print help menu
# p - print partition table
# n - add new partition
# d - delete partition
# t - change partition type
# w - write table to disk and exit
# q - quit without saving changes
# l - list known partition types
# a - toggle bootable flag
# v - verify partition table
# x - extra functionality (experts only)

Core Options

Display Options

# List partition tables for all devices
fdisk -l

# List partition tables for specific device
fdisk -l /dev/sda

# List partition tables for multiple devices
fdisk -l /dev/sda /dev/sdb /dev/sdc

# Use colored output
fdisk --color=always -l

# Disable colored output
fdisk --color=never -l

# List partition types
fdisk -l -t gpt /dev/sda
fdisk -l -t dos /dev/sda

Size Display Options

# Show sizes in sectors (default)
fdisk -l -u=sectors /dev/sda

# Show sizes in cylinders
fdisk -l -u=cylinders /dev/sda

# Display sizes in human-readable format
fdisk -l -H /dev/sda

# Display sizes in specific units
fdisk -l -S 4096 /dev/sda  # 4KB sector size

Compatibility Options

# DOS compatibility mode (deprecated)
fdisk -c=dos /dev/sda

# CHS mode disabled (default)
fdisk -c=nondos /dev/sda

# Force DOS compatibility
fdisk -C 1024 /dev/sda

Partition Management

Creating Partitions

# Interactive partition creation
fdisk /dev/sda
# Then: n (new), p (primary), 1 (partition number), [Enter], [Enter], w (write)

# Create primary partition
echo -e "n\np\n1\n\n\nw" | fdisk /dev/sda

# Create extended partition
echo -e "n\ne\n2\n\n\nw" | fdisk /dev/sda

# Create logical partition
echo -e "n\nl\n\n\nw" | fdisk /dev/sda

# Create partition with specific size
echo -e "n\np\n1\n\n+10G\nw" | fdisk /dev/sda

# Create partition from sector X to Y
echo -e "n\np\n1\n2048\n+20971520\nw" | fdisk /dev/sda

Deleting Partitions

# Delete partition interactively
fdisk /dev/sda
# Then: d (delete), 1 (partition number), w (write)

# Script partition deletion
echo -e "d\n1\nw" | fdisk /dev/sda

# Delete all partitions
echo -e "o\nw" | fdisk /dev/sda  # DOS
echo -e "g\nw" | fdisk /dev/sda  # GPT

Modifying Partition Types

# Change partition type interactively
fdisk /dev/sda
# Then: t (type), 1 (partition), 83 (Linux), w (write)

# Common partition type codes (MBR/DOS):
# 0C - Windows 95 FAT32 (LBA)
# 07 - NTFS/exFAT
# 82 - Linux swap
# 83 - Linux filesystem
# 8e - Linux LVM
# fd - Linux raid auto
# ef - EFI System Partition

# Set Linux filesystem type
echo -e "t\n1\n83\nw" | fdisk /dev/sda

# Set swap partition type
echo -e "t\n2\n82\nw" | fdisk /dev/sda

# Set LVM partition type
echo -e "t\n3\n8e\nw" | fdisk /dev/sda

# Set EFI partition type
echo -e "t\n1\nef\nw" | fdisk /dev/sda

GPT Partition Management

GPT Operations

# Create new GPT partition table
echo -e "g\nw" | fdisk /dev/sda

# Convert MBR to GPT
fdisk /dev/sda
# Then: g (GPT), w (write)

# List GPT partition types
fdisk /dev/sda
# Then: l (list types)

# Common GPT partition type GUIDs:
# 1 - EFI System
# 20 - Linux filesystem
# 19 - Linux swap
# 43 - Linux LVM
# 29 - Linux RAID

# Create EFI system partition
echo -e "n\n1\n\n+512M\nt\n1\nw" | fdisk /dev/sda

# Create Linux filesystem partition
echo -e "n\n2\n\n\nt\n2\n20\nw" | fdisk /dev/sda

GPT Attributes

# Set GPT attributes
fdisk /dev/sda
# Then: x (expert), A (attributes), partition number, attribute bit

# Common GPT attributes:
# Bit 0 - Platform required
# Bit 2 - Legacy BIOS bootable
# Bit 60 - Read-only
# Bit 62 - Hidden
# Bit 63 - No automount

Advanced Partition Operations

Partition Alignment

# Check partition alignment
fdisk -l /dev/sda | grep "^/dev"

# Create aligned partitions (1MiB alignment)
fdisk /dev/sda
# Start partition at sector 2048 (1MiB)

# Check if partition is aligned
blockdev --getalignoff /dev/sda1

# Get optimal I/O size
blockdev --getioopt /dev/sda

# Get physical block size
blockdev --getpbsz /dev/sda

Boot Flag Management

# Toggle bootable flag
fdisk /dev/sda
# Then: a (toggle boot), 1 (partition), w (write)

# Set boot flag via script
echo -e "a\n1\nw" | fdisk /dev/sda

# Check boot flag status
fdisk -l /dev/sda | grep "*"

Partition Label Management

# Set disk label (MBR)
echo -e "o\nw" | fdisk /dev/sda

# Set disk label (GPT)
echo -e "g\nw" | fdisk /dev/sda

# Set disk label (SGI)
echo -e "s\nw" | fdisk /dev/sda

# Set disk label (SUN)
echo -e "S\nw" | fdisk /dev/sda

# Set disk label (BSD)
echo -e "b\nw" | fdisk /dev/sda

Expert Mode Features

Expert Commands

# Enter expert mode
fdisk /dev/sda
# Then: x (expert mode)

# Expert mode commands:
# b - move beginning of data in partition
# c - change number of cylinders
# d - print raw partition table
# e - list extended partitions
# f - fix partition order
# g - create IRIX partition table
# h - change number of heads
# i - change disk identifier
# l - show partition chain
# m - print expert menu
# p - print partition table
# q - quit without saving
# r - return to main menu
# s - change number of sectors
# v - verify partition table
# w - write table to disk and exit

Disk Geometry Modification

# Change number of cylinders
fdisk /dev/sda
# x, c, <number>, r, w

# Change number of heads
fdisk /dev/sda
# x, h, <number>, r, w

# Change number of sectors per track
fdisk /dev/sda
# x, s, <number>, r, w

# Display current geometry
fdisk -l /dev/sda | grep "Geometry"

Disk Identifier Management

# Change disk identifier
fdisk /dev/sda
# x, i, 0x12345678, r, w

# Generate random disk identifier
fdisk /dev/sda
# x, i, r, w

# Display disk identifier
fdisk -l /dev/sda | grep "Disk identifier"

# Set specific identifier
echo -e "x\ni\n0x$(openssl rand -hex 4)\nr\nw" | fdisk /dev/sda

Scripting and Automation

Non-Interactive Operations

# Complete partition setup script
cat << 'EOF' | fdisk /dev/sda
o
n
p
1

+10G
n
p
2

+20G
n
p
3


t
2
82
t
3
8e
a
1
w
EOF

# GPT partition setup
cat << 'EOF' | fdisk /dev/sda
g
n
1

+512M
n
2

+10G
n
3


t
1
1
t
2
20
t
3
43
w
EOF

Using sfdisk for Scripting

# Dump partition layout
sfdisk -d /dev/sda > sda.layout

# Restore partition layout
sfdisk /dev/sdb < sda.layout

# Create partitions from script
cat << 'EOF' | sfdisk /dev/sda
label: dos
device: /dev/sda
unit: sectors

/dev/sda1 : start=2048, size=20971520, type=83, bootable
/dev/sda2 : start=20973568, size=41943040, type=82
/dev/sda3 : start=62916608, type=8e
EOF

Batch Operations

# Partition multiple disks identically
for disk in /dev/sd{b..f}; do
  echo -e "o\nn\np\n1\n\n\nw" | fdisk "$disk"
done

# Create standard layout on multiple disks
partition_disk() {
  local disk=$1
  cat << EOF | fdisk "$disk"
o
n
p
1

+512M
n
p
2

+10G
n
p
3


t
2
82
a
1
w
EOF
}

for disk in /dev/sd{b..d}; do
  partition_disk "$disk"
done

Information Display

Partition Table Display

# Show partition table
fdisk -l /dev/sda

# Show partition table with sizes in sectors
fdisk -l -u=sectors /dev/sda

# Show only partition information (no header)
fdisk -l /dev/sda | grep "^/dev"

# Show free space
fdisk -l /dev/sda | grep "free"

# Compact output
fdisk -l /dev/sda 2>/dev/null | awk '/^\/dev/{print $1, $5, $6}'

Device Information

# Show disk size
fdisk -l /dev/sda | grep "Disk /dev/sda"

# Show sector size
fdisk -l /dev/sda | grep "Sector size"

# Show I/O size
fdisk -l /dev/sda | grep "I/O size"

# Show disklabel type
fdisk -l /dev/sda | grep "Disklabel type"

# Show disk identifier
fdisk -l /dev/sda | grep "Disk identifier"

Partition Analysis

# Check partition alignment
fdisk -l /dev/sda | awk '/^\/dev/{
  start=$2;
  if (start % 2048 == 0)
    print $1 " is aligned"
  else
    print $1 " is NOT aligned (starts at " start ")"
}'

# Calculate partition sizes
fdisk -l /dev/sda | awk '/^\/dev/{
  print $1, "Size:", $(NF-1), $NF
}'

# List partition types
fdisk -l /dev/sda | awk '/^\/dev/{
  print $1, "Type:", $6
}'

Verification and Validation

Partition Table Verification

# Verify partition table
fdisk /dev/sda
# Then: v (verify), q (quit)

# Check for errors
echo -e "v\nq" | fdisk /dev/sda 2>&1 | grep -i error

# Validate partition boundaries
echo -e "v\nq" | fdisk /dev/sda

# Check partition order
fdisk -l /dev/sda | grep "^/dev" | sort -k2 -n

Data Integrity Checks

# Compare partition tables
diff <(fdisk -l /dev/sda) <(fdisk -l /dev/sdb)

# Backup partition table
dd if=/dev/sda of=sda_mbr.bin bs=512 count=1

# Restore partition table
dd if=sda_mbr.bin of=/dev/sda bs=512 count=1

# Verify backup
cmp -n 512 /dev/sda sda_mbr.bin

Troubleshooting

Common Issues

# Re-read partition table
partprobe /dev/sda

# Force kernel to re-read partition table
blockdev --rereadpt /dev/sda

# Check if device is busy
lsof /dev/sda
fuser -mv /dev/sda

# Fix partition order
fdisk /dev/sda
# x, f, r, w

# Recover from interrupted fdisk
# Use backup partition table
sfdisk --force /dev/sda < backup.layout

Error Recovery

# Disk label error recovery
# Create new label
echo -e "o\nw" | fdisk /dev/sda  # MBR
echo -e "g\nw" | fdisk /dev/sda  # GPT

# Fix GPT backup
sgdisk -e /dev/sda

# Restore MBR from backup
dd if=mbr_backup.bin of=/dev/sda bs=512 count=1
sync
partprobe /dev/sda

# Check partition table consistency
fdisk -l /dev/sda
gdisk -l /dev/sda
parted /dev/sda print

Device Access Issues

# Check device permissions
ls -l /dev/sda

# Verify device exists
test -b /dev/sda && echo "Block device exists"

# Check for device errors
dmesg | grep -i "sda"

# Verify disk is readable
dd if=/dev/sda of=/dev/null bs=512 count=1

# Check SMART status
smartctl -H /dev/sda

Integration with Other Tools

LVM Integration

# Prepare disk for LVM
echo -e "n\np\n1\n\n\nt\n1\n8e\nw" | fdisk /dev/sda
pvcreate /dev/sda1
vgcreate vg_data /dev/sda1

# Create multiple PV partitions
cat << 'EOF' | fdisk /dev/sda
o
n
p
1

+50G
n
p
2


t
1
8e
t
2
8e
w
EOF
pvcreate /dev/sda1 /dev/sda2

RAID Integration

# Prepare disks for RAID
for disk in /dev/sd{b..e}; do
  echo -e "o\nn\np\n1\n\n\nt\n1\nfd\nw" | fdisk "$disk"
done

# Create RAID array
mdadm --create /dev/md0 --level=5 --raid-devices=4 \
  /dev/sdb1 /dev/sdc1 /dev/sdd1 /dev/sde1

Encryption Integration

# Prepare partition for LUKS
echo -e "n\np\n1\n\n\nw" | fdisk /dev/sda
cryptsetup luksFormat /dev/sda1
cryptsetup luksOpen /dev/sda1 encrypted_data

# Create encrypted swap
echo -e "n\np\n2\n\n+8G\nt\n2\n82\nw" | fdisk /dev/sda
cryptsetup luksFormat /dev/sda2

Best Practices

Partition Layout Strategies

# Standard desktop layout
cat << 'EOF' | fdisk /dev/sda
o
n
p
1

+512M
n
p
2

+8G
n
p
3


t
1
83
t
2
82
t
3
83
a
1
w
EOF
# /dev/sda1 - /boot (512M)
# /dev/sda2 - swap (8G)
# /dev/sda3 - / (remaining)

# Server with separate /var
cat << 'EOF' | fdisk /dev/sda
o
n
p
1

+512M
n
p
2

+8G
n
p
3

+50G
n
e
4


n

+100G
n


t
1
83
t
2
82
t
3
83
t
5
83
t
6
83
a
1
w
EOF
# /dev/sda1 - /boot
# /dev/sda2 - swap
# /dev/sda3 - /
# /dev/sda5 - /var
# /dev/sda6 - /home

Alignment Guidelines

# Modern disk alignment (1MiB)
# Start partitions at sector 2048
# Size in multiples of 2048 sectors

# Check optimal alignment
blockdev --getalignoff /dev/sda1  # Should be 0
blockdev --getioopt /dev/sda      # Optimal I/O size

# SSD alignment (ensure TRIM support)
cat /sys/block/sda/queue/discard_max_bytes

Safety Practices

# Always backup partition table before changes
sfdisk -d /dev/sda > /root/sda_partition_backup.txt
dd if=/dev/sda of=/root/sda_mbr.bin bs=512 count=1

# Verify changes before writing
fdisk /dev/sda
# Make changes, then 'p' to print, verify, then 'w'

# Use wipefs before repartitioning
wipefs -a /dev/sda

# Check for mounted filesystems
mount | grep /dev/sda
lsof /dev/sda

Performance Considerations

Optimization Tips

# Use GPT for disks > 2TB
echo -e "g\nw" | fdisk /dev/sda

# Align partitions to 1MiB boundaries
# Start at sector 2048 (1MiB)

# For SSDs, ensure TRIM is enabled
hdparm -I /dev/sda | grep TRIM
fstrim -v /

# Check I/O scheduler
cat /sys/block/sda/queue/scheduler

# Set I/O scheduler for SSD
echo "noop" > /sys/block/sda/queue/scheduler

Monitoring Operations

# Monitor partition operations
watch -n 1 'fdisk -l /dev/sda'

# Check partition creation status
tail -f /var/log/syslog | grep sda

# Monitor kernel messages
dmesg -w | grep sda

# Check partition table changes
inotifywait -m /dev/sda

Security Considerations

Secure Erasure

# Wipe partition table
dd if=/dev/zero of=/dev/sda bs=512 count=1
sync

# Secure wipe with random data
dd if=/dev/urandom of=/dev/sda bs=1M count=100

# Use wipefs
wipefs -af /dev/sda

# Overwrite specific partition
dd if=/dev/zero of=/dev/sda1 bs=1M status=progress

Access Control

# Restrict fdisk access (root only)
chmod 700 $(which fdisk)

# Audit partition changes
auditctl -w /usr/sbin/fdisk -p x -k partition_changes

# Log all fdisk operations
alias fdisk='logger -t fdisk "$(whoami) - $@"; fdisk'

System Integration

Systemd Integration

# Create service to check partitions on boot
cat > /etc/systemd/system/check-partitions.service << 'EOF'
[Unit]
Description=Check Partition Tables
Before=local-fs.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/fdisk -l
StandardOutput=journal

[Install]
WantedBy=multi-user.target
EOF

systemctl enable check-partitions.service

Udev Rules

# Create udev rule for new partitions
cat > /etc/udev/rules.d/99-partition-notify.rules << 'EOF'
SUBSYSTEM=="block", ACTION=="add", ENV{DEVTYPE}=="partition", \
  RUN+="/usr/local/bin/notify-partition.sh %k"
EOF

# Reload udev rules
udevadm control --reload-rules

Reporting and Documentation

Generating Reports

# Complete disk report
fdisk -l > /tmp/disk_report_$(date +%Y%m%d).txt

# Partition summary
fdisk -l | grep -E "^Disk /dev/|^/dev/" > partition_summary.txt

# JSON output (with jq processing)
fdisk -l /dev/sda | awk '/^\/dev/{
  print "{\"device\":\"" $1 "\",\"start\":" $2 ",\"end\":" $3 ",\"sectors\":" $4 ",\"size\":\"" $(NF-1) " " $NF "\"}"
}' | jq -s '.'

# HTML report
fdisk -l | awk 'BEGIN{print "<html><body><pre>"} {print} END{print "</pre></body></html>"}' > report.html

Documentation Generation

# Create partition documentation
cat > /root/partition_layout.md << EOF
# Partition Layout for $(hostname)
Date: $(date)

## Disk: /dev/sda
$(fdisk -l /dev/sda)

## Mount Points
$(df -h | grep /dev/sda)

## Filesystem Types
$(lsblk -f /dev/sda)
EOF

Advanced Use Cases

Multi-Disk Management

# Clone partition layout to multiple disks
SOURCE_LAYOUT=$(sfdisk -d /dev/sda)
for disk in /dev/sd{b..f}; do
  echo "$SOURCE_LAYOUT" | sed "s/sda/$(basename $disk)/g" | sfdisk "$disk"
done

# Create identical JBOD setup
for disk in /dev/sd{b..f}; do
  echo -e "o\nn\np\n1\n\n\nt\n1\n83\nw" | fdisk "$disk"
  mkfs.ext4 -L "data_$(basename $disk)1" "${disk}1"
done

Partition Resizing Preparation

# Check partition before resize
fdisk -l /dev/sda1
df -h /dev/sda1
dumpe2fs -h /dev/sda1 | grep "Block count"

# Delete and recreate partition (larger)
# CAUTION: Backup data first!
fdisk /dev/sda
# d, 1, n, p, 1, <same start sector>, <new end>, w
partprobe /dev/sda
e2fsck -f /dev/sda1
resize2fs /dev/sda1

Disaster Recovery

# Create complete disk backup
dd if=/dev/sda of=/backup/sda_full.img bs=1M status=progress

# Backup only partition table
sfdisk -d /dev/sda > /backup/sda_partitions.dump
dd if=/dev/sda of=/backup/sda_mbr.bin bs=512 count=1

# Restore partition table
sfdisk /dev/sda < /backup/sda_partitions.dump
# OR
dd if=/backup/sda_mbr.bin of=/dev/sda bs=512 count=1
partprobe /dev/sda

# Verify restoration
fdisk -l /dev/sda

Environment Variables

# Set default fdisk behavior
export FDISK_NO_COLOR=1          # Disable colors
export FDISK_USE_CYLINDERS=0     # Don't use cylinders
export LIBFDISK_DEBUG=all        # Enable debug output

# Set specific terminal for fdisk
export TERM=xterm-256color

Exit Codes

# 0 - Success
# 1 - General error
# 2 - Usage error
# 3 - Cannot read partition table
# 4 - Cannot write partition table

# Check exit code
fdisk -l /dev/sda
if [ $? -eq 0 ]; then
  echo "Success"
else
  echo "Failed with code $?"
fi

Compatibility Notes

Legacy Systems

# DOS compatibility mode (old systems)
fdisk -c=dos /dev/sda

# Cylinder mode (very old systems)
fdisk -u=cylinders /dev/sda

# Maximum compatibility MBR
echo -e "o\nn\np\n1\n\n\nt\n1\n83\na\n1\nw" | fdisk -c=dos /dev/sda

Modern Systems

# GPT for UEFI systems
echo -e "g\nw" | fdisk /dev/sda

# Large sector size (4K native)
fdisk -b 4096 /dev/sda

# NVMe devices
fdisk /dev/nvme0n1

Related Commands

  • sfdisk - Scriptable partition table manipulator
  • cfdisk - Curses-based partition table manipulator
  • gdisk/sgdisk - GPT partition table manipulator
  • parted - GNU partition editor
  • partprobe - Inform OS of partition table changes
  • lsblk - List block devices
  • blkid - Locate/print block device attributes
  • blockdev - Call block device ioctls

Examples Collection

Example 1: Basic Partition Creation

# Create single partition using entire disk
(
echo o # Create DOS partition table
echo n # New partition
echo p # Primary partition
echo 1 # Partition number
echo   # First sector (default)
echo   # Last sector (default)
echo w # Write changes
) | fdisk /dev/sdb

Example 2: Multi-Partition Layout

# Create boot, swap, and root partitions
(
echo o
echo n
echo p
echo 1
echo
echo +512M
echo n
echo p
echo 2
echo
echo +8G
echo n
echo p
echo 3
echo
echo
echo t
echo 2
echo 82
echo a
echo 1
echo w
) | fdisk /dev/sdb

Example 3: GPT UEFI System

# Create GPT layout for UEFI boot
(
echo g
echo n
echo 1
echo
echo +512M
echo n
echo 2
echo
echo +8G
echo n
echo 3
echo
echo
echo t
echo 1
echo 1
echo t
echo 2
echo 19
echo t
echo 3
echo 20
echo w
) | fdisk /dev/sdb

# Format partitions
mkfs.vfat -F32 /dev/sdb1  # EFI
mkswap /dev/sdb2           # Swap
mkfs.ext4 /dev/sdb3        # Root

Example 4: LVM Setup

# Prepare disk for LVM
(
echo o
echo n
echo p
echo 1
echo
echo
echo t
echo 8e
echo w
) | fdisk /dev/sdb

# Create LVM structures
pvcreate /dev/sdb1
vgcreate vg_main /dev/sdb1
lvcreate -L 20G -n lv_root vg_main
lvcreate -L 10G -n lv_home vg_main
lvcreate -l 100%FREE -n lv_data vg_main

Example 5: RAID Preparation

# Prepare multiple disks for RAID
for disk in sdb sdc sdd sde; do
  (
  echo o
  echo n
  echo p
  echo 1
  echo
  echo
  echo t
  echo fd
  echo w
  ) | fdisk /dev/$disk
done

# Create RAID5 array
mdadm --create /dev/md0 --level=5 --raid-devices=4 \
  /dev/sdb1 /dev/sdc1 /dev/sdd1 /dev/sde1

See Also

  • fdisk(8) - Linux man page
  • sfdisk(8) - Script-friendly fdisk
  • cfdisk(8) - Curses fdisk
  • gdisk(8) - GPT fdisk
  • parted(8) - Partition editor
  • partx(8) - Tell kernel about partition changes

Version Information

# Check fdisk version
fdisk --version

# Check for features
fdisk --help | grep -i gpt

Summary

fdisk is the traditional and most widely used partition table manipulator for Linux systems. While it supports both MBR and GPT partition tables, it's primarily known for its interactive mode and MBR handling. For GPT operations, gdisk/sgdisk might be more appropriate, and for scripting, sfdisk provides better automation capabilities. Always backup partition tables before making changes and verify operations before writing to disk.