In our today’s guide, we are going to learn how to manage partitions and filesystems on Linux. A partition is a logical subset of the physical disk, and information about partitions are stored in a partition table. This table includes information about the first and last sectors of the partition and its type, and further details on each partition. Normally on any operating system, a disk needs to be partitioned before it can be used for their required purposes.  Partitions are seen by an operating system as a separate “disks”, even if they all reside in the same physical media. On Linux each partition is assigned to a directory under /dev, like /dev/sda1 or /dev/sda2.

There are two main ways of storing partition information on hard disks;

  • MBR (Master Boot Record), and
  • GPT (GUID Partition Table).

MBR and GPT Partitioning System

MBR

The partition table is stored on the first sector of a disk, called the Boot Sector, along with a boot loader, which on Linux systems is usually the GRUB bootloader. But MBR has a series of limitations that hinder its use on modern systems, like the inability to address disks of more than 2 TB in size, and the limit of only 4 primary partitions per disk.

GPT

A partitioning system that addresses many of the limitations of MBR. There is no practical limit on disk size, and the maximum number of partitions are limited only by the operating system itself. It is more commonly found on more modern machines that use UEFI instead of the old PC BIOS.

Below are the tools used to manage MBR and GPT Systems;

fdisk

It is used to manipulate disk partition table. fdisk is a dialog-driven program for creation and manipulation of partition tables. It understands GPT, MBR, Sun, SGI and BSD partition tables. Block devices can be divided into one or more logical disks called partitions. This division is recorded in the partition table, usually found in sector 0 of the disk. (In the BSD world one talks about `disk slices’ and a `disklabel’.)

gdisk

gdisk an interactive GUID partition table (GPT) manipulator. GPT fdisk (gdisk) is a text-mode menu-driven program for creation and manipulation of partition tables. It will automatically convert an old-style Master Boot Record (MBR) partition table or BSD disklabel stored without an MBR carrier partition to the newer Globally Unique Identifier (GUID) Partition Table (GPT) format, or will load a GUID partition table. When used with the -l command-line option, the program displays the current partition table and then exits.

parted

parted a partition manipulation program. parted is a program to manipulate disk partitions. It supports multiple partition table formats, including MS-DOS and GPT. It is useful for creating space for new operating systems, reorganising disk usage, and copying data to new hard disks.

mkfs

mkfs is used to build a Linux filesystem on a device, usually a hard disk partition. The device argument is either the device name (e.g. /dev/hda1, /dev/sdb2), or a regular file that shall contain the filesystem. The size argument is the number of blocks to be used for the filesystem.

mkswap

mkswap sets up a Linux swap area on a device or in a file. The device argument will usually be a disk partition (something like /dev/sdb7) but can also be a file. The Linux kernel does not look at partition IDs, but many installation scripts will assume that partitions of hex type 82 (LINUX_SWAP) are meant to be swap partitions.

Manage MBR and GPT Partition Tables

Managing MBR Partitions with fdisk

The standard utility for managing MBR partitions on Linux is fdisk.

Syntax;

fdisk [options] device
fdisk -l [device...]

Keep in mind that you need to specify the device corresponding to the physical disk, not one of its partitions (like /dev/sda1). When invoked as root or having user privilege permission (sudo) , fdisk will show a greeting, then a warning and it will wait for your commands.

$ sudo fdisk /dev/sdb
[sudo] password for frank: 

Welcome to fdisk (util-linux 2.34).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0x2c02bf0d.

Command (m for help):

You can create, edit or delete partitions at will, but nothing will be written to disk unless you use the write (w) command. So you can “practice” without risk of losing data, as long as you stay clear of the w key. To exit fdisk without saving changes, use the q command.

Creating a Partition

Primary vs Extended Partitions

On an MBR disk, you can have 2 main types of partitions, primary and extended. Like we said before, you can have only 4 primary partitions on the disk, and if you want to make the disk “bootable”, the first partition must be a primary one. One way to work around this limitation is to create an extended partition that acts as a container for logical partitions. You could have, for example, a primary partition, an extended partition occupying the remainder of the disk space and five logical partitions inside it.

For an operating system like Linux, primary and extended partitions are treated exactly in the same way, so there are no “advantages” of using one over the other.

To create a partition, use the n command. By default, partitions will be created at the start of unallocated space on the disk. You will be asked for the partition type (primary or extended), first sector and last sector. For the first sector, you can usually accept the default value suggested by fdisk, you can specify a size followed by the letters 

  • K-Kilobyte
  • M-Megabyte
  • G-Gigabyte
  • T-Terabyte
  • P-Petabyte

To create a 5 GB partition, you could specify +5G as the Last sector, and fdisk will size the partition accordingly.

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-32383919, default 2048): 2048
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-32383919, default 32383919): +5G

Created a new partition 1 of type 'Linux' and of size 5 GiB.

Printing the Current Partition Table

The command p is used to print the current partition table. i.e

Command (m for help): p
Disk /dev/sdb: 15.45 GiB, 16580567040 bytes, 32383920 sectors
Disk model: VBOX HARDDISK   
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: dos
Disk identifier: 0x78a00bfe

Device     Boot Start      End  Sectors Size Id Type
/dev/sdb1        2048 10487807 10485760   5G 83 Linux

The above command have the following columns;

  • Device: The device assigned to the partition.
  • Boot: Shows whether the partition is “bootable” or not.
  • Start: The sector where the partition starts.
  • End: The sector where the partition ends.
  • Sectors: The total number of sectors in the partition. Multiply it by the sector size to get the partition size in bytes.
  • Size: The size of the partition in “human readable” format. In the example above, values are in gigabytes.
  • Id: The numerical value representing the partition type.
  • Type: The description for the partition type.

Checking for Unallocated Space

Use the F command to show how much free space on the disk.

Command (m for help): F
Unpartitioned space /dev/sdb: 10.45 GiB, 11210809344 bytes, 21896112 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes

   Start      End  Sectors  Size
10487808 32383919 21896112 10.5G

Changing the Partition Type

First of all, you can see a list of all the valid codes by using the command l.

Command (m for help): l

 0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris        
 1  FAT12           27  Hidden NTFS Win 82  Linux swap / So c1  DRDOS/sec (FAT-
 2  XENIX root      39  Plan 9          83  Linux           c4  DRDOS/sec (FAT-
 3  XENIX usr       3c  PartitionMagic  84  OS/2 hidden or  c6  DRDOS/sec (FAT-
 4  FAT16 <32M      40  Venix 80286     85  Linux extended  c7  Syrinx         
 5  Extended        41  PPC PReP Boot   86  NTFS volume set da  Non-FS data    
 6  FAT16           42  SFS             87  NTFS volume set db  CP/M / CTOS / .
 7  HPFS/NTFS/exFAT 4d  QNX4.x          88  Linux plaintext de  Dell Utility   
 8  AIX             4e  QNX4.x 2nd part 8e  Linux LVM       df  BootIt         
 9  AIX bootable    4f  QNX4.x 3rd part 93  Amoeba          e1  DOS access     
 a  OS/2 Boot Manag 50  OnTrack DM      94  Amoeba BBT      e3  DOS R/O        
 b  W95 FAT32       51  OnTrack DM6 Aux 9f  BSD/OS          e4  SpeedStor      
 c  W95 FAT32 (LBA) 52  CP/M            a0  IBM Thinkpad hi ea  Rufus alignment
 e  W95 FAT16 (LBA) 53  OnTrack DM6 Aux a5  FreeBSD         eb  BeOS fs        
 f  W95 Ext'd (LBA) 54  OnTrackDM6      a6  OpenBSD         ee  GPT            
10  OPUS            55  EZ-Drive        a7  NeXTSTEP        ef  EFI (FAT-12/16/
11  Hidden FAT12    56  Golden Bow      a8  Darwin UFS      f0  Linux/PA-RISC b
12  Compaq diagnost 5c  Priam Edisk     a9  NetBSD          f1  SpeedStor      
14  Hidden FAT16 <3 61  SpeedStor       ab  Darwin boot     f4  SpeedStor      
16  Hidden FAT16    63  GNU HURD or Sys af  HFS / HFS+      f2  DOS secondary  
17  Hidden HPFS/NTF 64  Novell Netware  b7  BSDI fs         fb  VMware VMFS    
18  AST SmartSleep  65  Novell Netware  b8  BSDI swap       fc  VMware VMKCORE 
1b  Hidden W95 FAT3 70  DiskSecure Mult bb  Boot Wizard hid fd  Linux raid auto
1c  Hidden W95 FAT3 75  PC/IX           bc  Acronis FAT32 L fe  LANstep        
1e  Hidden W95 FAT1 80  Old Minix       be  Solaris boot    ff  BBT

Now, you may need to change the partition type, especially when dealing with disks that will be used on other operating systems and platforms. This is done with the command t, followed by the number of the partition you wish to change.

Command (m for help): t
Partition number (1,2, default 2): 2
Hex code (type L to list all codes): 82

Changed type of partition 'Linux' to 'Linux swap / Solaris'.

In the above output, we have changed partition no 2 to Hex code 82 which is “Linux swap / Solaris“.

Deleting Partitions

To delete a partition, use the d command. fdisk will ask you for the number of the partition you want to delete, unless there is only one partition on the disk. In this case, this partition will be selected and deleted immediately. Be aware that if you delete an extended partition, all the logical partitions inside it will also be deleted.

Command (m for help): d
Partition number (1,2, default 2): 2

Partition 2 has been deleted.

Displaying Help

Use m command to display help about fdisk utility.

Help:

  DOS (MBR)
   a   toggle a bootable flag
   b   edit nested BSD disklabel
   c   toggle the dos compatibility flag

  Generic
   d   delete a partition
   F   list free unpartitioned space
   l   list known partition types
   n   add a new partition
   p   print the partition table
   t   change a partition type
   v   verify the partition table
   i   print information about a partition

  Misc
   m   print this menu
   u   change display/entry units
   x   extra functionality (experts only)

  Script
   I   load disk layout from sfdisk script file
   O   dump disk layout to sfdisk script file

  Save & Exit
   w   write table to disk and exit
   q   quit without saving changes

  Create a new label
   g   create a new empty GPT partition table
   G   create a new empty SGI (IRIX) partition table
   o   create a new empty DOS partition table
   s   create a new empty Sun partition table

Managing GUID Partitions with gdisk

gdisk utility is equivalent to fdisk when dealing with GPT partitioned disks. Its interface is modeled after fdisk with an interactive prompt somehow with the similar commands.

Syntax;

gdisk [ -l ] device

Creating a Partition

The command to create a partition is n, just as in fdisk. The main difference is that besides the partition number and the first and last sector (or size), you can also specify the partition type during the creation. GPT partitions support many more types than MBR. You can check a list of all the supported types by using the L command.

checking list of partition types;

Command (? for help): L
Type search string, or <Enter> to show all codes: 
0700 Microsoft basic data                0c01 Microsoft reserved                
2700 Windows RE                          3000 ONIE boot                         
3001 ONIE config                         3900 Plan 9                            
4100 PowerPC PReP boot                   4200 Windows LDM data                  
4201 Windows LDM metadata                4202 Windows Storage Spaces            
7501 IBM GPFS                            7f00 ChromeOS kernel                   
7f01 ChromeOS root                       7f02 ChromeOS reserved                 
8200 Linux swap                          8300 Linux filesystem                  
8301 Linux reserved                      8302 Linux /home                       
8303 Linux x86 root (/)                  8304 Linux x86-64 root (/)             
8305 Linux ARM64 root (/)                8306 Linux /srv                        
8307 Linux ARM32 root (/)                8308 Linux dm-crypt                    
8309 Linux LUKS                          830a Linux IA-64 root (/)              
830b Linux x86 root verity               830c Linux x86-64 root verity          
830d Linux ARM32 root verity             830e Linux ARM64 root verity           
830f Linux IA-64 root verity             8310 Linux /var                        
8311 Linux /var/tmp                      8400 Intel Rapid Start                 
8500 Container Linux /usr                8501 Container Linux resizable rootfs  
8502 Container Linux /OEM customization  8503 Container Linux root on RAID      
8e00 Linux LVM                           a000 Android bootloader                
a001 Android bootloader 2                a002 Android boot 1

creating a partition;

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

Printing the Current Partition Table

The command p is used to print the current partition table;

Command (? for help): p
Disk /dev/sdb: 32383920 sectors, 15.4 GiB
Model: VBOX HARDDISK   
Sector size (logical/physical): 512/512 bytes
Disk identifier (GUID): BE06D161-C972-574F-B995-10A9697882FF
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 2048, last usable sector is 32383886
Partitions will be aligned on 2048-sector boundaries
Total free space is 15604623 sectors (7.4 GiB)

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048        10487807   5.0 GiB     8300  Linux filesystem
   2        10487808        16779263   3.0 GiB     8302  Linux /home

In the above output, we have find that;

  • Each disk has a unique Disk Identifier (GUID). This is a 128 bit hexadecimal number, assigned randomly when the partition table is created. Since there are 3.4 × 1038 possible values to this number, the chances that 2 random disks have the same GUID are pretty slim. The GUID can be used to identify which filesystems to mount at boot time (and where), eliminating the need to use the device path to do so (like /dev/sdb).
  • See the phrase Partition table holds up to 128 entries? That’s right, you can have up to 128 partitions on a GPT disk. Because of this, there is no need for primary and extended partitions.
  • The free space is listed on the last line, so there is no need for an equivalent of the F command from fdisk.

Deleting a Partition

To delete a partition, type d and the partition number. Unlike fdisk, the first partition will not be automatically selected if it is the only one on the disk. On GPT disks, partitions can be easily reordered, or “sorted”, to avoid gaps in the numbering sequence. To do this, simply use the s command. i.e

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048        10487807   5.0 GiB     8300  Linux filesystem
   2        10487808        16779263   3.0 GiB     8302  Linux /home
   3        16779264        25167871   4.0 GiB     8300  Linux filesystem

Now, let’s delete the second partition;

Command (? for help): d
Partition number (1-3): 2

After deleting the second partition, the table will look like this;

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048        10487807   5.0 GiB     8300  Linux filesystem
   3        16779264        25167871   4.0 GiB     8300  Linux filesystem

If you use the s command, it would become;

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048        10487807   5.0 GiB     8300  Linux filesystem
   2        16779264        25167871   4.0 GiB     8300  Linux filesystem

We notice that the third partition became the second one.

Recovery Options

GPT disks store backup copies of the GPT header and partition table, making it easy to recover disks in case this data has been damaged. gdisk provides features to aid in those recovery tasks, accessed with the r command.

You can rebuild a corrupt main GPT header or partition table with b and c, respectively, or use the main header and table to rebuild a backup with d and e. You can also convert a MBR to a GPT with f, and do the opposite with g, among other operations. Type ? in the recovery menu to get a list of all the available recovery commands and descriptions about what they do.

Displaying Help

Use ? command to display help about gdisk utility.

Command (? for help): ?
b	back up GPT data to a file
c	change a partition's name
d	delete a partition
i	show detailed information on a partition
l	list known partition types
n	add a new partition
o	create a new empty GUID partition table (GPT)
p	print the partition table
q	quit without saving changes
r	recovery and transformation options (experts only)
s	sort partitions
t	change a partition's type code
v	verify disk
w	write table to disk and exit
x	extra functionality (experts only)
?	print this menu

Managing MBR and GPT Partitions with parted

GNU parted is used to create, delete, move, resize, rescue and copy partitions. It is very powerful partition editor and work with both GPT and MBR disks, and cover almost all disk management needs. There are many graphical front-ends that make working with parted much easier, like GParted for GNOME-based desktop environments and the KDE Partition Manager for KDE Desktops.

Syntax;

parted [options] [device [command [options...]...]]

To start using parted is by type parted DEVICE, where DEVICE is the device you want to manage (parted /dev/sdb). The program starts an interactive command line interface like fdisk and gdisk with a (parted) prompt for you to enter commands.

$ sudo parted /dev/sdb
GNU Parted 3.3
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)

Be careful! If you do not specify a device, parted will automatically select the primary disk (usually /dev/sda) to work with.

Selecting Disks

To switch to a different disk than the one specified on the command line, you can use the select command, followed by the device name;

(parted) select /dev/sdb
Using /dev/sdb

Creating a Partition Table on an Empty Disk

To create a partition table on an empty disk, use the mklabel command, followed by the partition table type that you want to use. There are many supported partition table types, but the main types you should know of are msdos which is used here to refer to an MBR partition table, and gpt to refer to a GPT partition table.

To create an MBR partition table, type:

(parted) mklabel msdos

To create an GPT partition table, type:

(parted) mklabel gpt

In our case we are going to create a GPT partition table.

(parted) mklabel gpt                                             
Warning: The existing disk label on /dev/sdb will be destroyed and all data on this disk will be lost. Do you want to continue?
Yes/No? Yes                                                               
(parted)

Creating a Partition

mkpart command is used to create a partition.

Syntax;

mkpart PARTTYPE FSTYPE START END

where:

PARTTYPE: Is the partition type, which can be primarylogical or extended in case an MBR partition table is used.

FSTYPE: Specifies which filesystem will be used on this partition. Note that parted will not create the filesystem. It just sets a flag on the partition which tells the OS what kind of data to expect from it.

START: Specifies the exact point on the device where the partition begins. You can use different units to specify this point. 2s can be used to refer to the second sector of the disk, while 1m refers to the beginning of the first megabyte of the disk. Other common units are B (bytes) and % (percentage of the disk).

END: Specifies the end of the partition. Note that this is not the size of the partition, this is the point on the disk where it ends. For example, if you specify 100m the partition will end 100 MB after the start of the disk. You can use the same units as in the START parameter.

example;

(parted) mkpart primary ext4 1m 5g

The above command creates a primary partition of type ext4, starting at the first megabyte of the disk, and ending after the 5th gigabyte.

Getting Information of The Disk

The print command can be used to get more information about a specific partition or even all of the block devices (disks) connected to your system.

To get information about the currently selected partition, just type print;

(parted) print                                                            
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sdb: 16.6GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system  Name     Flags
 1      1049kB  5000MB  4999MB               primary
 2      5000MB  10.0GB  5001MB               primary

(parted) 

To list of all block devices connected to your system use print devices;

(parted) print devices                                                    
/dev/sdb (16.6GB)
/dev/sda (26.8GB)

To get information about all connected devices at once, you can use print all;

(parted) print all                                                        
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sdb: 16.6GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system  Name     Flags
 1      1049kB  5000MB  4999MB               primary
 2      5000MB  10.0GB  5001MB               primary


Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sda: 26.8GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags: 

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  26.8GB  26.8GB  primary  ext4         boot

To know how much free space there is in each one of them, you can use print free;

(parted) print free                                                       
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sdb: 16.6GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system  Name     Flags
        17.4kB  1049kB  1031kB  Free Space
 1      1049kB  5000MB  4999MB               primary
 2      5000MB  10.0GB  5001MB               primary
        10.0GB  16.6GB  6580MB  Free Space

Removing a Partition

To remove a partition, use the command rm followed by the partition number, which you can display using the print command. to remove partition 1 use rm 1 command;

(parted) rm 1 

We can confirm with print command;

(parted) print                                                            
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sdb: 16.6GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system  Name     Flags
 2      5000MB  10.0GB  5001MB               primary

The output above shows only partition 2 meaning that partition has been removed with rm 1 command.

Recovering Partitions

parted can recover a deleted partition. We can recover removed partition 1 above. To recover it, you can use the rescue command, with the syntax; rescue START END, where START is the approximate location where the partition started, and END the approximate location where it ended.

parted will scan the disk in search of partitions, and offer to restore any that are found. In the example above the partition 1 started at 1039kB and ended at 5010 MB. So you can use the following command to recover the partition;

(parted) rescue 1039k 5010m
Information: A ext4 primary partition was found at 1049kB -> 5000MB.
Do you want to add it to the partition table?

Yes/No/Cancel? y

Creating Filesystems

After partitioning the disk, you will need to format the partition with a filesystem before using it to store data. A filesystem controls how the data is stored and accessed on the disk. Linux supports many filesystems, some native, like the ext (Extended Filesystem) family, while others come from other operating systems like FAT from MS-DOS, NTFS from Windows NT, HFS and HFS+ from Mac OS, etc.

The standard tool used to create a filesystem on Linux is mkfs.

Creating an ext2/ext3/ext4 Filesystem

The Extended Filesystem (ext) was the first filesystem for Linux, and through the years was replaced by new versions called ext2, ext3 and ext4, which is currently the default filesystem for many Linux distributions. The utilities mkfs.ext2mkfs.ext3 and mkfs.ext4 are used to create ext2, ext3 and ext4 filesystems. In fact, all of these “utilities” exist only as symbolic links to another utility called mke2fsmke2fs alters its defaults according to the name it is called by. As such, they all have the same behavior and command line parameters.

Syntax;

mkfs.ext2 TARGET

Where TARGET is the name of the partition where the filesystem should be created. For example, to create an ext3 filesystem on /dev/sdb1 the command would be:

$ sudo mkfs.ext3 /dev/sdb1
[sudo] password for frank: 
mke2fs 1.45.5 (07-Jan-2020)
Creating filesystem with 1220352 4k blocks and 305216 inodes
Filesystem UUID: be97e047-699f-485c-a9fa-ff0c94e44f4e
Superblock backups stored on blocks: 
	32768, 98304, 163840, 229376, 294912, 819200, 884736

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done

Instead of using the command corresponding to the filesystem you wish to create, you can pass the -t parameter to mke2fs followed by the filesystem name. For example, the following commands are equivalent, and will create an ext4 filesystem on /dev/sdb2.

$ sudo mke2fs -t ext4 /dev/sdb2
mke2fs 1.45.5 (07-Jan-2020)
Creating filesystem with 1220864 4k blocks and 305216 inodes
Filesystem UUID: f8b045c7-f29a-4873-989a-e5ec938e338c
Superblock backups stored on blocks: 
	32768, 98304, 163840, 229376, 294912, 819200, 884736

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done

Command Line Parameters

mke2fs supports a wide range of command line parameters and options. Here are some of the most significant ones. All of them also apply to mkfs.ext2mkfs.ext3 and mkfs.ext4:

  • -b SIZE: Sets the size of the data blocks in the device to SIZE, which can be 1024, 2048 or 4096 bytes per block.
  • -c: Checks the target device for bad blocks before creating the filesystem. You can run a thorough, but much slower check by passing this parameter twice, as in mkfs.ext4 -c -c TARGET.
  • -d DIRECTORY: Copies the contents of the specified directory to the root of the new filesystem. Useful if you need to “pre-populate” the disk with a predefined set of files.
  • -F: Danger, Will Robinson! This option will force mke2fs to create a filesystem, even if the other options passed to it or the target are dangerous or make no sense at all. If specified twice (as in -F -F) it can even be used to create a filesystem on a device which is mounted or in use, which is a very, very bad thing to do.
  • -L VOLUME_LABEL: Will set the volume label to the one specified in VOLUME_LABEL. This label must be at most 16 characters long.
  • -n: This is a truly useful option that simulates the creation of the filesystem, and displays what would be done if executed without the n option. Think of it as a “trial” mode. Good to check things out before actually committing any changes to disk.
  • -q: Quiet mode. mke2fs will run normally, but will not produce any output to the terminal. Useful when running mke2fs from a script.
  • -U ID: This will set the UUID (Universally Unique Identifier) of a partition to the value specified as ID. UUIDs are 128 bit numbers in hexadecimal notation that serve to uniquely identify a partition to the operating system. This number is specified as a 32-digit string in the format 8-4-4-4-12, meaning 8 digits, hyphen, 4 digits, hyphen, 4 digits, hyphen, 4 digits, hyphen, 12 digits, like D249E380-7719-45A1-813C-35186883987E. Instead of an ID you can also specify parameters like clear to clear the filesystem UUID, random, to use a randomly generated UUID, or time to create a time-based UUID.
  • -V: Verbose mode, prints much more information during operation than usual. Useful for debugging purposes.

Creating an XFS Filesystem

XFS is a high-performance filesystem originally developed by Silicon Graphics in 1993 for its IRIX operating system. Due to its performance and reliability features, it is commonly used for servers and other environments that require high (or guaranteed) filesystem bandwidth. Tools for managing XFS filesystems are part of the xfsprogs package.

Syntax;

sudo mkfs.xfs TARGET

where TARGET is the partition you want the filesystem to be created in. For example:

$ sudo mkfs.xfs -f /dev/sdb1
meta-data=/dev/sdb1              isize=512    agcount=4, agsize=305088 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=0
         =                       reflink=1
data     =                       bsize=4096   blocks=1220352, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1
log      =internal log           bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0

mkfs.xfs supports a number of command line options. Here are some of the most common ones.

  • -b size=VALUE: Sets the block size on the filesystem, in bytes, to the one specified in VALUE. The default value is 4096 bytes (4 KiB), the minimum is 512, and the maximum is 65536 (64 KiB).
  • -m crc=VALUE: Parameters starting with -m are metadata options. This one enables (if VALUE is 1) or disables (if VALUE is 0) the use of CRC32c checks to verify the integrity of all metadata on the disk. This enables better error detection and recovery from crashes related to hardware issues, so it is enabled by default. The performance impact of this check should be minimal, so normally there is no reason to disable it.
  • -m uuid=VALUE: Sets the partition UUID to the one specified as VALUE. Remember that UUIDs are 32-character (128 bits) numbers in hexadecimal base, specified in groups of 8, 4, 4, 4 and 12 digits separated by dashes, like 1E83E3A3-3AE9-4AAC-BF7E-29DFFECD36C0.
  • -f: Force the creation of a filesystem on the target device even if a filesystem is detected on it.
  • -l logdev=DEVICE: This will put the log section of the filesystem on the specified device, instead of inside the data section.
  • -l size=VALUE: This will set the size of the log section to the one specified in VALUE. The size can be specified in bytes, and suffixes like m or g can be used. -l size=10m, for example, will limit the log section to 10 Megabytes.
  • -q: Quiet mode. In this mode, mkfs.xfs will not print the parameters of the file system being created.
  • -L LABEL: Sets the filesystem label, which can be at most 12 characters long.
  • -N: Similar to the -n parameter of mke2fs, will make mkfs.xfs print all the parameters for the creation of the file system, without actually creating it.

Creating a FAT or VFAT Filesystem

The FAT filesystem originated from MS-DOS, and through the years has received many revisions culminating on the FAT32 format released in 1996 with Windows 95 OSR2. VFAT is an extension of the FAT16 format with support for long (up to 255 characters) file names. Both filesystems are handled by the same utility, mkfs.fatmkfs.vfat is an alias to it.

Syntax;

mkfs.vfat TARGET

where TARGET is the partition you want the filesystem to be created in. For example:

$ sudo mkfs.vfat /dev/sdb1
[sudo] password for frank: 
mkfs.fat 4.1 (2017-01-24)

mkfs.fat supports a number of command line options. Below are the most important ones. A full list and description of every option can be read in the manual for the utility, with the command man mkfs.fat.

  • -c: Checks the target device for bad blocks before creating the filesystem.
  • -C FILENAME BLOCK_COUNT: Will create the file specified in FILENAME and then create a FAT filesystem inside it, effectively creating an empty “disk image”, that can be later written to a device using a utility such as dd or mounted as a loopback device. When using this option, the number of blocks in the filesystem (BLOCK_COUNT) must be specified after the device name.
  • -F SIZE: Selects the size of the FAT (File Allocation Table), between 12, 16 or 32, i.e., between FAT12, FAT16 or FAT32. If not specified, mkfs.fat will select the appropriate option based on the filesystem size.
  • -n NAME: Sets the volume label, or name, for the filesystem. This can be up to 11 characters long, and the default is no name.
  • -v: Verbose mode. Prints much more information than usual, useful for debugging.

Creating an exFAT Filesystem

exFAT is a filesystem created by Microsoft in 2006 that addresses one of the most important limitations of FAT32: file and disk size. On exFAT, the maximum file size is 16 exabytes (from 4 GB on FAT32), and the maximum disk size is 128 petabytes. As it is well supported by all three major operating systems (Windows, Linux and mac OS), it is a good choice where interoperability is needed, like on large capacity flash drives, memory cards and external disks. In fact, it is the default filesystem, as defined by the SD Association, for SDXC memory cards larger than 32 GB. The default utility for creating exFAT filesystems is mkfs.exfat, which is a link to mkexfatfs.

Syntax;

mkfs.exfat TARGET

where TARGET is the partition you want the filesystem to be created in. For example:

$ sudo mkfs.exfat /dev/sdb1
mkexfatfs 1.3.0
Creating... done.
Flushing... done.
File system created successfully.

mkfs.exfat has very few command line options. They are:

  • -i VOL_ID: Sets the Volume ID to the value specified in VOL_ID. This is a 32-Bit hexadecimal number. If not defined, an ID based on the current time is set.
  • -n NAME: Sets the volume label, or name. This can have up to 15 characters, and the default is no name.
  • -p SECTOR: Specifies the first sector of the first partition on the disk. This is an optional value, and the default is zero.
  • -s SECTORS: Defines the number of physical sectors per cluster of allocation. This must be a power of two, like 1, 2, 4, 8, and so on.

Understanding Btrfs Filesystem

Btrfs (officially the B-Tree Filesystem, pronounced as “Butter FS”, “Better FS” or even “Butterfuss”, your pick) is a filesystem that has been in development since 2007 specifically for Linux by the Oracle Corporation and other companies, including Fujitsu, Red Hat, Intel and SUSE, among others.

Btrfs Features

There are many features that make Btrfs attractive these are;

  • multiple device support (including striping, mirroring and striping+mirroring, as in a RAID setup)
  • transparent compression
  • SSD optimizations
  • incremental backups
  • snapshots
  • online defragmentation
  • offline checks
  • support for subvolumes (with quotas)
  • deduplication

As it is a copy-on-write filesystem it is very resilient to crashes. And on top of that, Btrfs is simple to use, and well supported by many Linux distributions. And some of them, like SUSE, use it as the default filesystem.

Creating a Btrfs Filesystem

The utility mkfs.btrfs is used to create a Btrfs filesystem. Using the command without any options creates a Btrfs filesystem on a given device. Example;

$ sudo mkfs.btrfs -f /dev/sdb1
btrfs-progs v5.4.1 
See http://btrfs.wiki.kernel.org for more information.

Label:              (null)
UUID:               0b3ee380-5ec2-4c3a-b52f-d7c8bf0ca905
Node size:          16384
Sector size:        4096
Filesystem size:    4.66GiB
Block group profiles:
  Data:             single            8.00MiB
  Metadata:         DUP             256.00MiB
  System:           DUP               8.00MiB
SSD detected:       no
Incompat features:  extref, skinny-metadata
Checksum:           crc32c
Number of devices:  1
Devices:
   ID        SIZE  PATH
    1     4.66GiB  /dev/sdb1

Use the -L to set a label (or name) for your filesystem. Btrfs labels can have up to 256 characters, except for newlines:

example:

$ sudo mkfs.btrfs /dev/sdb1 -f -L "My Disk"
btrfs-progs v5.4.1 
See http://btrfs.wiki.kernel.org for more information.

Label:              My Disk
UUID:               3462dabf-5e1b-4615-bbb9-54697c9d9b42
Node size:          16384
Sector size:        4096
Filesystem size:    4.66GiB
Block group profiles:
  Data:             single            8.00MiB
  Metadata:         DUP             256.00MiB
  System:           DUP               8.00MiB
SSD detected:       no
Incompat features:  extref, skinny-metadata
Checksum:           crc32c
Number of devices:  1
Devices:
   ID        SIZE  PATH
    1     4.66GiB  /dev/sdb1

Managing Subvolumes

Subvolumes are like filesystems inside filesystems. Think of them as a directory which can be mounted as (and treated like) a separate filesystem. Subvolumes make organization and system administration easier, as each one of them can have separate quotas or snapshot rules.

Suppose you have a Btrfs filesystem mounted on /mnt, and you wish to create a subvolume inside it to store your backups. Let’s call it Mmfile:

$ sudo btrfs subvolume create /mnt/Mmfile
Create subvolume '/mnt/Mmfile'

We can list the contents of /mnt with ls -alh command;

$ ls -alh /mnt
total 20K
drwxr-xr-x  1 root root   12 May 14 11:51 .
drwxr-xr-x 20 root root 4.0K Apr 28 11:29 ..
drwxr-xr-x  1 root root    0 May 14 12:55 Mmfile

We can check that the subvolume is active;

$ sudo btrfs subvolume show /mnt/Mmfile/
Mmfile
	Name: 			Mmfile
	UUID: 			8a218887-c3ab-cd49-ba1e-960ce4aa6b54
	Parent UUID: 		-
	Received UUID: 		-
	Creation time: 		2021-05-14 12:55:57 +0300
	Subvolume ID: 		257
	Generation: 		7
	Gen at creation: 	7
	Parent ID: 		5
	Top level ID: 		5
	Flags: 			-
	Snapshot(s):

Compression

Btrfs supports transparent file compression, with three different algorithms available to the user. This is done automatically on a per-file basis, as long as the filesystem is mounted with the -o compress option. The algorithms are smart enough to detect incompressible files and will not try to compress them, saving system resources. So on a single directory you may have compressed and uncompressed files together. The default compression algorithm is ZLIB, but LZO (faster, worse compression ratio) or ZSTD (faster than ZLIB, comparable compression) are available, with multiple compression levels.

Creating Swap Partitions

On Linux, the system can swap memory pages from RAM to disk as needed, storing them on a separate space usually implemented as a separate partition on a disk, called the swap partition or simply swap. This partition needs to be of a specific type, and set-up with a proper utility (mkswap) before it can be used.

Using fdisk and gdisk we can create a swap partition as follows;

  • On fdisk use the t command. Select the partition you want to use and change its type to 82. Write changes to disk and quit with w.
  • On gdisk the command to change the partition type is also t, but the code is 8200. Write changes to disk and quit with w.

Using parted, the partition should be identified as a swap partition during creation, just use linux-swap as the filesystem type. For example, the command to create a 800 MB swap partition, starting at 100 MB on disk is:

$ sudo parted
[sudo] password for frank: 
GNU Parted 3.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) select /dev/sdb                                                  
Using /dev/sdb
(parted) mkpart primary linux-swap 101m 900m                              
Warning: You requested a partition from 101MB to 900MB (sectors 197265..1757812).
The closest location we can manage is 10.0GB to 10.0GB (sectors 19531776..19531776).
Is this still acceptable to you?
Yes/No? yes                                                               
(parted)

Use mkswap followed by the device representing the partition you want to use, i.e

$ sudo mkswap /dev/sdb2                                       
mkswap: /dev/sdb2: warning: wiping old swap signature.
Setting up swapspace version 1, size = 4.7 GiB (5000654848 bytes)
no label, UUID=cb8d194a-7e91-478b-a056-3a14bdc926e2

We can use swapon command to enable swap;

$ sudo swapon /dev/sdb3

We can use swapoff command to disable swap;

$ sudo swapoff /dev/sdb3

Linux also supports the use of swap files instead of partitions. Just create an empty file of the size you want using dd and then use mkswap and swapon with this file as the target.

The following commands will create a 1 GB file called swap2 in the current directory, filled with zeroes, and than set-up and enable it as a swap file.

Create the swap file:

$ dd if=/dev/zero of=swap2 bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 18.0524 s, 59.5 MB/s
  • if= is the input file, the source of the data that will be written to the file. In this case it is the /dev/zero device, which provides as many NULL characters as requested.
  • of= is the output file, the file that will be created.
  • bs= is the size of the data blocks, here specified in Megabytes.
  • count= is the amount of blocks to be written to the output. 1024 blocks of 1 MB each equals 1 GB.

Use mkswap command to create swap from swap2 file;

$ mkswap swap2
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=74f0abfc-a1c2-4329-8ee3-6a442bcf81dd

We can now use swapon command to enable swap;

$ swapon swap2

Note: Both mkswap and swapon will complain if your swap file has insecure permissions. The recommended file permission flag is 0600. Owner and group should be root.i.e

$ swapon swap2
swapon: /home/frank/swap2: insecure permissions 0664, 0600 suggested.
swapon: /home/frank/swap2: insecure file owner 1000, 0 (root) suggested.
swapon: /home/frank/swap2: swapon failed: Operation not permitted

Using the commands above, this swap file will be used only during the current system session. If the machine is rebooted, the file will still be available, but will not be automatically loaded. You can automate that by adding the new swap file to /etc/fstab.

Conclusion

You’ve learned how to Manage Partitions and Filesystems on Linux. We hope this guide was of help to you.

Similar articles:

LPIC 101 Search Text Files on Linux Using Regular Expressions

LPIC 101 – Processing Text Streams Using Filters on Linux

LPIC 101 – Compress and Uncompress Files Using tar, gzip, bzip2

LPIC 101 – Managing Files and Directories on Linux Terminal

LPIC 101 – Changing Runlevels and Boot Targets on Linux System