Last modified: August 04, 2024

This article is written in: 🇺🇸

Partitioning disks

Partitioning a disk means dividing the disk into smaller areas called partitions. Each partition can store different types of data or provide extra storage. There are two main partition tables: MBR (Master Boot Record) and GPT (GUID Partition Table).

+------------------+------------------+------------------+-----------------+-----------------+
| Partition        | /dev/sda1        | /dev/sda2        | /dev/sda3       | Free Space      |
+------------------+------------------+------------------+-----------------+-----------------+
| Filesystem       | ext4             | ext4             | swap            |                 |
+------------------+------------------+------------------+-----------------+                 |
| Mount Point      | /                | /home            |                 |                 |
+------------------+------------------+------------------+-----------------+                 |
| Size             | 50GB             | 100GB            | 8GB             | 42GB            |
+------------------+------------------+------------------+-----------------+-----------------+

You can perform the following operations with partitions:

Relationship between Physical Disks and Partitions

The relationship between physical disks (like hard drives or SSDs) and partitions is managed through a device naming convention and a series of abstractions that allow the operating system to handle storage efficiently. Physical disks are the actual hardware components where data is stored. They can be hard disk drives (HDDs), solid-state drives (SSDs), or other storage devices. These disks are identified by device names such as /dev/sda, /dev/sdb, etc.

+-------------------+
| Physical Disk 1  |
|    (/dev/sda)     |
|                   |
|  +-------------+  |
|  | Partition 1 |  |
|  | (/dev/sda1) |  |
|  +-------------+  |
|  | Partition 2 |  |
|  | (/dev/sda2) |  |
|  +-------------+  |
+-------------------+

+-------------------+
| Physical Disk 2  |
|    (/dev/sdb)     |
|                   |
|  +-------------+  |
|  | Partition 1 |  |
|  | (/dev/sdb1) |  |
|  +-------------+  |
|  | Partition 2 |  |
|  | (/dev/sdb2) |  |
|  +-------------+  |
+-------------------+

+-------------------+
| Physical Disk 3  |
|    (/dev/sdc)     |
|                   |
|  +-------------+  |
|  | Partition 1 |  |
|  | (/dev/sdc1) |  |
|  +-------------+  |
|  | Partition 2 |  |
|  | (/dev/sdc2) |  |
|  +-------------+  |
+-------------------+

Partitions are divisions of a physical disk, each of which can be formatted with a file system and used for different purposes. Each partition is also represented as a device file but with an additional number indicating the partition:

Common Disk Naming Conventions

Disk names typically follow a specific naming pattern to indicate the type of device, its order, and its partitions. Here's a breakdown:

I Device Type Indicators

The first few letters of the disk name indicate the type of device:

II Device Order

The last letter before any numbers denotes the order of the device:

III Partition Number

Numbers following the device identifier indicate the partition index:

Additional Remarks

This naming convention helps to identify and manage disks and partitions in various systems and environments efficiently.

Partition Types

Primary Partitions

Extended Partitions

Logical Partitions

MBR and GPT

Below is a table comparing both formats:

Feature GPT (GUID Partition Table) MBR (Master Boot Record)
Maximum Partition Size 18.8 million TB (with 512B sector size) 2 TB (with 512B sector size)
Maximum Number of Partitions 128 partitions per disk (typically) 4 primary partitions per disk
Data Recovery Stores multiple copies of the partitioning and boot data across the disk for resilience. Stores only one copy of the partitioning and boot data at the beginning of the disk, making it more prone to data loss.
Compatibility Supported by newer operating systems and modern hardware (UEFI). Universally compatible with all operating systems and BIOS.
Boot Process Works with UEFI (Unified Extensible Firmware Interface) which is a modern method of booting. Works with BIOS (Basic Input/Output System) which is traditional and older.
Partition Scheme Uses globally unique identifiers (GUIDs) for partitions. Uses a traditional partition table.
Advantages Higher limits on partition sizes and counts, better data resilience, required for modern hardware (like larger hard drives). Universal compatibility, simplicity, and well-tested over time.
Disadvantages Not compatible with older systems that only support BIOS. Limited partition size and count, less resilient against data corruption.

Looking at partition tables

To look at a disk's partition table, use the gdisk or fdisk command. The gdisk command is for GPT partitions, while fdisk can be used for both MBR and GPT partitions. To see all disk partitions, use:

fdisk -l

Here's an example of what this output might look like:

Disk /dev/sda: 500 GiB, 536870912000 bytes, 1048576000 sectors
Disk model: Samsung SSD 860
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 2F3C4D5E-6F7A-4B8B-9C7D-2E1F12345678

Device        Start        End   Sectors   Size Type
/dev/sda1      2048     534527    532480   260M EFI System
/dev/sda2    534528    1050623    515096   251M Linux filesystem
/dev/sda3   1050624  209715199 208664576  99.5G Linux filesystem
/dev/sda4 209715200  419430399 209715200   100G Linux filesystem
/dev/sda5 419430400 1048575967 628145568 299.5G Linux filesystem

Explanation:

Managing Disk Partitions

To manage disk partitions in Linux, you can use tools like fdisk, parted, or lsblk. Here's a guide on how to handle the tasks you've mentioned, with examples and explanations:

Checking Partition Types

To differentiate between primary, extended, and logical partitions, we need to check for the partition number and consider that extended partitions are typically numbered within 1-4 but are treated separately from primary partitions. Here's a command that will list all the partitions on your system along with their types:

lsblk -o NAME,TYPE | awk '
$2 == "part" {
    if ($1 ~ /[1-4]$/) {
        if ($1 ~ /[0-9]p[0-9]$/) {
            part_type = "primary"
        } else {
            part_type = "extended"
        }
    } else {
        part_type = "logical"
    }
    print "/dev/" $1, part_type
}'

Example output:

/dev/├─sda1 primary
/dev/└─sda2 primary

To determine whether a specific partition is primary, extended, or logical, you can use the following script. This script takes a partition path (like /dev/sda1) and outputs its type:

partition_path="/dev/sda1"  # Replace with user-provided partition path
lsblk -no TYPE $partition_path | awk '
/part/ {
    if ("'"$partition_path"'" ~ /[0-9]p?[1-4]$/) {
        if ("'"$partition_path"'" ~ /[0-9]p[1-4]$/) {
            print "primary"
        } else {
            print "extended"
        }
    } else if ("'"$partition_path"'" ~ /[0-9]p?[5-9][0-9]*$/) {
        print "logical"
    } else {
        print "unknown"
    }
}'

Replace /dev/sda1 with the specific partition path the user provides. The script will output "primary," "extended," or "logical" accordingly.

Checking Free Space

To check how much free space is available on the disk run sudo parted /dev/sda print free.

Example output:

Model: ATA Disk (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system  Name                  Flags
        17,4kB  1049kB  1031kB  Free Space
 1      1049kB  538MB   537MB   fat32        EFI System Partition  boot, esp
 2      538MB   500GB   500GB   ext4
        500GB   500GB   1056kB  Free Space

The Free Space line indicates unallocated space. In this case 1056kB.

Creating a New Partition

Let's assume we currently have the following primary partitions: /dev/sda1 and /dev/sda2. We want to create a new partition layout with /dev/sda3 as a primary partition, /dev/sda4 as an extended partition, and /dev/sda5 through /dev/sda7 as logical partitions within the extended partition. To accomplish this, you can use partitioning tools such as parted, fdisk, or gdisk. Below are the steps for each tool:

Using parted

I. Start parted

sudo parted /dev/sda

II. Create the Third Primary Partition (/dev/sda3)**

(parted) mkpart primary ext4 40GiB 60GiB

III. Create the Extended Partition (/dev/sda4)

(parted) mkpart extended 60GiB 100%

IV. Create Logical Partitions (/dev/sda5, /dev/sda6, /dev/sda7)

(parted) mkpart logical ext4 60GiB 70GiB
(parted) mkpart logical ext4 70GiB 80GiB
(parted) mkpart logical ext4 80GiB 90GiB

V. Exit parted

(parted) quit

Using fdisk

I. Start fdisk

sudo fdisk /dev/sda

II. Create the Third Primary Partition (/dev/sda3)

Command (m for help): n

III. Create the Extended Partition (/dev/sda4)**

Command (m for help): n

IV. Create Logical Partitions (/dev/sda5, /dev/sda6, /dev/sda7)

Command (m for help): n

V. Write Changes

Command (m for help): w

Using gdisk

I. Start gdisk

sudo gdisk /dev/sda

II. Create the Third Primary Partition (/dev/sda3)

Command (? for help): n

III. Create the Extended Partition (/dev/sda4)**

Command (? for help): n

IV. Create Logical Partitions (/dev/sda5, /dev/sda6, /dev/sda7)

Command (? for help): n

V. Write Changes

Command (? for help): w

This writes changes to disk and exits gdisk.

Resizing Partitions

Resizing partitions involves either expanding or shrinking an existing partition. This can be done using tools like parted, fdisk, and gdisk, though some tools are better suited for certain tasks. Here are the detailed steps and considerations for each tool:

Using parted

I. Start parted

sudo parted /dev/sda

II. Check Partition Table

(parted) print

This lists all partitions and their details.

III. Resize Partition

(parted) resizepart PARTITION_NUMBER END

IV. Exit parted

(parted) quit

Using fdisk

Note: fdisk does not support resizing partitions directly. You need to delete the partition and recreate it with the new size. This can be risky and should be done with caution.

I. Start fdisk

sudo fdisk /dev/sda

II. List Partitions

Command (m for help): p

This displays the current partition table.

III. Delete the Partition

Command (m for help): d

IV. Recreate the Partition with New Size

Command (m for help): n

V. Write Changes

Command (m for help): w

This writes the new partition table and exits fdisk.

VI. Resize Filesystem (if needed)

After resizing the partition, you may need to resize the filesystem to fill the new partition size using tools like resize2fs for ext4 filesystems.

Using gdisk

I. Start gdisk**

sudo gdisk /dev/sda

II. List Partitions

Command (? for help): p

This lists current partitions.

III. Delete the Partition

Command (? for help): d

IV. Recreate the Partition with New Size

Command (? for help): n

V. Write Changes

Command (? for help): w

This writes changes to disk and exits gdisk.

VI. Resize Filesystem (if needed)

Use appropriate filesystem tools (e.g., resize2fs) to resize the filesystem to fit the new partition size.

Removing Partitions

Removing partitions is a critical task that should be done carefully to avoid data loss. The process varies slightly depending on the tool you use (parted, fdisk, or gdisk). Below are the instructions for each tool, along with notes on the expected outputs.

Using parted

I. Start parted

sudo parted /dev/sda

II. Check Partition Table

(parted) print

This lists all partitions and their details.

III. Remove Partition

(parted) rm PARTITION_NUMBER

IV. Exit parted

(parted) quit

Using fdisk

I. Start fdisk

sudo fdisk /dev/sda

II. List Partitions

Command (m for help): p

This displays the current partition table.

III. Delete Partition

Command (m for help): d

IV. Write Changes

Command (m for help): w

This writes the changes to the partition table and exits fdisk.

Using gdisk

I. Start gdisk

sudo gdisk /dev/sda

II. List Partitions

Command (? for help): p

This lists the current partitions.

III. Delete Partition

Command (? for help): d

IV. Write Changes

Command (? for help): w

This writes the changes to the disk and exits gdisk.

Changing MBR to GPT using gdisk

Sometimes, there's a need to change a disk from one partition table format to another. For instance, converting an MBR disk to a GPT format can be done using tools like gdisk or parted. Here's how to do it with gdisk:

Steps to Repartition a Disk Using gdisk with Expected Outputs

GPT fdisk (gdisk) version 1.0.6

Partition table scan:
MBR: protective
BSD: not present
APM: not present
GPT: present

Found valid GPT with protective MBR; using GPT.
Disk /dev/sda: 20971520 sectors, 10.0 GiB
Logical sector size: 512 bytes
Disk identifier (GUID): B7D5F9E3-3A74-4F56-B0D7-FB65DE571EC7
Partition table holds up to 128 entries
First usable sector is 34, last usable sector is 20971486
Partitions will be aligned on 2048-sector boundaries
Total free space is 10265 sectors (5.0 MiB)

Number  Start (sector)    End (sector)  Size       Code  Name
 1          2048         20951039   10.0 GiB    8300  Linux filesystem

GPT fdisk (gdisk) version 1.0.6

Type device filename, or press <enter> to exit: /dev/sda
Command (? for help):

Expert command (? for help):

About to wipe out GPT on /dev/sda. Proceed? (Y/N):

Confirm with 'y', then decide on blanking out the MBR:

Blank out MBR? (Y/N):

After confirming with 'y', the result will be:

GPT data structures destroyed! You may now partition the disk using the 'n' command.

Expert command (? for help): n

Creating new GPT data structure
Confirm creation of a new GPT by pressing 'y': Y

The system will acknowledge:

GPT data structures created successfully.

Command (? for help): n
Partition number (1-128, default 1): 1
First sector (34-20971486, default = 2048) or {+-}size{KMGTP}:
Last sector (2048-20971486, default = 20971486) or {+-}size{KMGTP}: +1G
Current type is 'Linux filesystem'
Hex code or GUID (L to show codes, Enter = 8300):

After defining the partitions, the prompt returns to:

Command (? for help):

Do you want to proceed? (Y/N): Y
Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING PARTITIONS!!

Do you want to proceed? (Y/N): Y

OK; writing new GUID partition table (GPT) to /dev/sda.
The operation has completed successfully.

GPT fdisk (gdisk) version 1.0.6

Partition table scan:
MBR: protective
BSD: not present
APM: not present
GPT: present

Found valid GPT with protective MBR; using GPT.
Disk /dev/sda: 20971520 sectors, 10.0 GiB
Logical sector size: 512 bytes
Disk identifier (GUID): 12345678-1234-1234-1234-1234567890AB
Partition table holds up to 128 entries
First usable sector is 34, last usable sector is 20971486
Partitions will be aligned on 2048-sector boundaries
Total free space is 1048576 sectors (512.0 MiB)

Number  Start (sector)    End (sector)  Size       Code  Name
 1          2048           2099199   1.0 GiB    8300  Linux filesystem
 2       2099200          20971519   9.0 GiB    8300  Linux filesystem

This output confirms that the new partitions are correctly set up.

🔴 Caution:

Important Notes

Challenges

  1. What are the key differences in terms of capacity, partition limits, and compatibility between MBR (Master Boot Record) and GPT (GUID Partition Table) partition tables?
  2. How can you list all the disk partitions on a Linux system?
  3. What are the steps to create a new partition on a disk using the fdisk command?
  4. What distinguishes primary partitions from extended partitions?
  5. How can you delete an existing partition using the fdisk command?
  6. Why is it necessary to create a filesystem on a disk partition?
  7. Is it possible to convert a disk from an MBR partition table to a GPT partition table and vice versa? If yes, how can this be achieved?
  8. What do the first two or three letters in common disk names (like /dev/sda, /dev/hda) signify?
  9. What information is conveyed by the last letter and the numbers in common disk names (e.g., /dev/sda1, /dev/sdc2)?
  10. What is the largest capacity of a disk that can be effectively partitioned using MBR and GPT partition tables, respectively?

Table of Contents

    Partitioning disks
    1. Relationship between Physical Disks and Partitions
    2. Common Disk Naming Conventions
      1. I Device Type Indicators
      2. II Device Order
      3. III Partition Number
      4. Additional Remarks
    3. Partition Types
    4. Primary Partitions
      1. Extended Partitions
      2. Logical Partitions
    5. MBR and GPT
    6. Looking at partition tables
    7. Managing Disk Partitions
      1. Checking Partition Types
      2. Checking Free Space
      3. Creating a New Partition
      4. Resizing Partitions
      5. Removing Partitions
      6. Changing MBR to GPT using gdisk
    8. Steps to Repartition a Disk Using gdisk with Expected Outputs
      1. Important Notes
    9. Challenges