0
0
Linux CLIscripting~15 mins

fdisk and lsblk in Linux CLI - Deep Dive

Choose your learning style9 modes available
Overview - fdisk and lsblk
What is it?
fdisk and lsblk are command-line tools used in Linux to manage and view disk drives and their partitions. fdisk allows you to create, delete, and modify partitions on a disk. lsblk shows a clear list of all block devices like disks and partitions in a tree format. Both help you understand and organize your storage devices.
Why it matters
Without tools like fdisk and lsblk, managing disk space would be confusing and error-prone. You wouldn't easily know how your disks are divided or how much space each part uses. This could lead to data loss or inefficient use of storage. These tools give you control and clarity over your computer's storage.
Where it fits
Before learning fdisk and lsblk, you should understand basic Linux commands and file system concepts. After mastering these tools, you can learn about mounting partitions, formatting disks, and automating disk management with scripts.
Mental Model
Core Idea
fdisk edits the blueprint of your disk partitions, while lsblk shows you the current layout of all storage devices.
Think of it like...
Imagine your hard drive as a large apartment building. fdisk is like the architect who draws and changes the floor plans (partitions), and lsblk is like the building directory that shows all apartments and their sizes.
┌─────────────┐       ┌─────────────┐
│   Disk      │──────▶│  Partitions │
│ (Hard Drive)│       │ (Rooms)     │
└─────────────┘       └─────────────┘
     ▲                      ▲
     │                      │
  fdisk edits           lsblk lists
  the partitions        the layout
Build-Up - 6 Steps
1
FoundationUnderstanding Disk and Partition Basics
🤔
Concept: Learn what disks and partitions are and why they matter.
A disk is a physical storage device. Partitions divide this disk into sections, like rooms in a house. Each partition can hold a file system, which organizes files. Without partitions, you can't separate data or install multiple operating systems.
Result
You know that disks hold data and partitions split disks into manageable parts.
Understanding disks and partitions is essential because all disk management commands work by changing or showing these parts.
2
FoundationListing Disks with lsblk
🤔
Concept: Use lsblk to see all disks and partitions in a clear tree format.
Run the command 'lsblk' in the terminal. It shows all block devices, their sizes, types (disk or partition), and mount points if any. This helps you see what storage devices your system recognizes.
Result
Example output: NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 232.9G 0 disk ├─sda1 8:1 0 500M 0 part /boot └─sda2 8:2 0 232.4G 0 part / sdb 8:16 0 931.5G 0 disk └─sdb1 8:17 0 931.5G 0 part /data
lsblk gives a quick, organized view of all storage devices, helping you understand your system's disk layout without making changes.
3
IntermediateExploring fdisk Interactive Mode
🤔
Concept: Learn how to use fdisk interactively to view and edit partitions.
Run 'sudo fdisk /dev/sdx' (replace x with your disk letter). Inside fdisk, you can type 'p' to print the partition table, 'n' to create a new partition, 'd' to delete one, and 'w' to write changes. This tool lets you modify the disk's partition layout safely.
Result
You can see the current partitions and create or delete partitions as needed.
Knowing fdisk's interactive commands lets you safely change disk partitions, which is critical for managing storage.
4
IntermediateComparing fdisk and lsblk Outputs
🤔Before reading on: Do you think fdisk and lsblk show the exact same information? Commit to yes or no.
Concept: Understand the difference between fdisk's and lsblk's views of disk partitions.
fdisk shows detailed partition tables including partition types and flags. lsblk shows a user-friendly tree of devices and mount points. fdisk is for editing; lsblk is for viewing. Both complement each other.
Result
You can interpret both outputs and know when to use each tool.
Recognizing that fdisk and lsblk serve different purposes prevents confusion and helps you choose the right tool for your task.
5
AdvancedUsing fdisk for Partition Table Types
🤔Before reading on: Do you think fdisk supports both MBR and GPT partition tables? Commit to yes or no.
Concept: Learn how fdisk handles different partition table types: MBR and GPT.
fdisk can manage both MBR (older) and GPT (modern) partition tables. You can create, delete, or convert partitions accordingly. GPT supports more partitions and larger disks. Use 'g' in fdisk to create a new GPT table, 'o' for MBR.
Result
You can manage disks with different partition schemes using fdisk.
Understanding partition table types is crucial for working with modern large disks and compatibility.
6
ExpertAutomating Disk Info with lsblk JSON Output
🤔Before reading on: Do you think lsblk can output data in JSON format for scripts? Commit to yes or no.
Concept: Discover how lsblk can output machine-readable JSON for automation.
Run 'lsblk -J' to get JSON output of all block devices. This is useful for scripts that need to parse disk info automatically. You can extract sizes, mount points, and device names programmatically.
Result
Example JSON snippet: { "blockdevices": [ {"name": "sda", "size": "232.9G", "children": [ {"name": "sda1", "mountpoint": "/boot"}, {"name": "sda2", "mountpoint": "/"} ]} ] }
Knowing lsblk's JSON output unlocks powerful automation possibilities for disk management in scripts.
Under the Hood
fdisk works by reading and modifying the partition table stored in the first sectors of a disk. This table tells the system where partitions start and end. lsblk reads the kernel's block device information from sysfs, showing devices and their relationships without changing anything.
Why designed this way?
fdisk was designed as a simple, interactive tool to safely edit partition tables, a critical and sensitive disk area. lsblk was created to provide a clear, non-destructive view of all block devices, helping users understand disk layouts without risk.
┌───────────────┐
│   Disk Device │
│   (e.g. /dev/sda) │
└──────┬────────┘
       │ Partition Table (MBR/GPT)
       ▼
┌───────────────┐
│   fdisk Tool  │
│  Reads/Writes │
└───────────────┘

┌───────────────┐
│   Kernel Sysfs│
│   Block Info  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│   lsblk Tool  │
│   Reads Only  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does running lsblk change your disk partitions? Commit to yes or no.
Common Belief:lsblk can modify or damage disk partitions because it shows detailed disk info.
Tap to reveal reality
Reality:lsblk only reads and displays disk info; it never changes anything on the disk.
Why it matters:Believing lsblk can change disks may cause unnecessary fear or avoidance of a safe tool.
Quick: Can fdisk safely edit partitions on a mounted disk? Commit to yes or no.
Common Belief:You can use fdisk to edit partitions on any disk, even if it's currently in use (mounted).
Tap to reveal reality
Reality:Editing mounted partitions with fdisk can cause data loss or corruption; partitions should be unmounted first.
Why it matters:Ignoring this can lead to serious data loss and system crashes.
Quick: Does fdisk support GPT partition tables fully? Commit to yes or no.
Common Belief:fdisk only works with old MBR partition tables and cannot handle GPT disks.
Tap to reveal reality
Reality:Modern fdisk versions support GPT partition tables, allowing full management of modern disks.
Why it matters:Not knowing this limits your ability to manage large or modern disks effectively.
Quick: Does lsblk show hidden or encrypted partitions by default? Commit to yes or no.
Common Belief:lsblk always shows every partition, including hidden or encrypted ones.
Tap to reveal reality
Reality:lsblk shows block devices recognized by the kernel; some encrypted or hidden partitions may not appear without special options.
Why it matters:Assuming lsblk shows everything can cause confusion when expected partitions are missing.
Expert Zone
1
fdisk's interactive mode can be scripted using echo and here-documents, but this is fragile compared to dedicated tools like parted or sfdisk.
2
lsblk's output depends on kernel device recognition; devices not properly initialized or with driver issues may not appear.
3
fdisk does not update the kernel's view of partitions until the disk is re-read or the system is rebooted, which can cause temporary inconsistencies.
When NOT to use
Avoid fdisk for scripting complex partitioning tasks; use parted or sfdisk instead for better automation. lsblk is not suitable for modifying disks; use it only for inspection. For encrypted or LVM volumes, specialized tools are needed.
Production Patterns
System administrators use lsblk in scripts to detect available disks before formatting. fdisk is used interactively during OS installation or recovery to fix partition tables. Automation often combines lsblk JSON output with parted for scripted disk setup.
Connections
Partition Table (MBR and GPT)
fdisk edits and reads partition tables; understanding these tables is essential to use fdisk correctly.
Knowing how partition tables work helps you avoid corrupting disks and understand fdisk's output.
Linux Filesystem Mounting
lsblk shows mount points, connecting physical partitions to where they appear in the file system.
Understanding mounting clarifies why some partitions appear with mount points and others do not.
Urban Planning
Like city planners divide land into zones, fdisk divides disks into partitions for organized use.
Seeing disk partitioning as land zoning helps grasp why careful planning prevents conflicts and data loss.
Common Pitfalls
#1Trying to create a new partition on a mounted disk.
Wrong approach:sudo fdisk /dev/sda Command (m for help): n Partition number (1-4): 3 First sector: (default) Last sector: (default) w
Correct approach:sudo umount /dev/sda3 sudo fdisk /dev/sda Command (m for help): n Partition number (1-4): 3 First sector: (default) Last sector: (default) w
Root cause:Not unmounting the partition before editing causes data corruption because the system is actively using the partition.
#2Assuming lsblk output shows all devices including uninitialized disks.
Wrong approach:lsblk # No output for a newly connected USB drive
Correct approach:sudo partprobe lsblk # Now the USB drive appears
Root cause:Kernel may not detect new devices immediately; running partprobe or re-plugging is needed.
#3Using fdisk on a GPT disk without knowing it, causing partition table confusion.
Wrong approach:sudo fdisk /dev/sda Command (m for help): o # This creates a new MBR table, wiping GPT data
Correct approach:sudo gdisk /dev/sda # Use gdisk for GPT disks to avoid data loss
Root cause:fdisk defaults to MBR and can overwrite GPT tables if used carelessly.
Key Takeaways
fdisk is a powerful tool to create and modify disk partitions but must be used carefully, especially on mounted disks.
lsblk provides a safe, clear view of all block devices and their relationships without changing anything.
Understanding partition tables (MBR vs GPT) is essential for effective disk management with fdisk.
Using lsblk's JSON output enables automation and scripting for disk inspection tasks.
Always unmount partitions before editing them and choose the right tool for your disk type to avoid data loss.