Manage Linux Partitions and Filesystems

CompTIABeginner
Practice Now

Introduction

In this lab, you will learn the fundamental skills required to manage disk partitions and filesystems in a Linux environment. You will work with command-line utilities like fdisk to inspect available disks, create new partitions, and format them with a standard filesystem. To ensure a safe learning experience, all operations will be performed on a dedicated secondary virtual disk, /dev/sdb, leaving the primary operating system disk untouched.

Note: In this lab environment, /dev/sdb is implemented as a loop device (a file that acts like a disk). When you create partitions, they will appear with names like loop13p1, but you'll create symbolic links to access them as /dev/sdb1, /dev/sdb2, etc., as you would with real hardware.

Throughout the exercises, you will create a standard Linux partition, format it with the ext4 filesystem, and learn how to mount it for immediate use. You will then configure the system to mount this filesystem automatically on boot by editing the /etc/fstab file. Finally, you will extend your skills by creating and managing a dedicated Linux swap partition, a critical component for system performance.

Inspect Disks and Create a New Linux Partition with fdisk

In this step, you will learn how to inspect the available disks and their partition tables. You will then use the fdisk utility, a powerful command-line tool, to create a new partition on a secondary disk. In a real-world scenario, you must be extremely careful when modifying partitions, as mistakes can lead to data loss. For this lab, we will work on a dedicated virtual disk, /dev/sdb, to ensure the main operating system disk (/dev/sda) remains untouched.

First, let's get an overview of all the block devices (disks and partitions) attached to your system. The lsblk command provides a clear, tree-like view.

lsblk

The output will show you the available disks, including your primary system disk (vda) and a loop device (loop13) that represents our virtual disk for this lab.

NAME       MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
...
loop13       7:13   0     2G  0 loop
vda        252:0    0    40G  0 disk
├─vda1     252:1    0     1M  0 part
├─vda2     252:2    0   200M  0 part /boot/efi
└─vda3     252:3    0  39.8G  0 part /

Notice that the loop device (which is accessible as /dev/sdb through a symbolic link) is a 2GB virtual disk with no partitions yet. Now, let's use fdisk to get a more detailed look at the partition table of /dev/sdb. The -l flag lists the partition tables for the specified devices and then exits. Since fdisk requires root privileges to inspect disk-level information, you must use sudo.

sudo fdisk -l /dev/sdb

The output provides details about the disk, including its size, sectors, and identifier. Since there are no partitions yet, the device list at the bottom will be empty.

Disk /dev/sdb: 2 GiB, 2147483648 bytes, 4194304 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Note: If this is the first time using the disk, you may see a message about creating a new DOS disklabel.

Next, you will start fdisk in its interactive mode to create a new partition. This process involves a sequence of single-letter commands. Run the following command to begin managing /dev/sdb:

sudo fdisk /dev/sdb

You are now inside the fdisk utility, indicated by the Command (m for help): prompt. Follow these steps carefully:

  1. Create a new partition: Type n and press Enter.
  2. Choose partition type: You'll be asked to select a partition type (primary or extended). The default is primary (p), which is what we want. Press Enter to accept the default.
  3. Choose partition number: The default is 1, as this is the first partition. Press Enter to accept it.
  4. Specify the first sector: The default value is the first available sector on the disk. This is almost always the correct choice. Press Enter to accept the default.
  5. Specify the last sector or size: Instead of calculating sectors, you can specify a human-readable size. Let's create a 500MB partition. Type +500M and press Enter.
  6. Print the in-memory partition table: Before saving, it's good practice to review your changes. Type p and press Enter to see the new partition layout. You should see a new device, /dev/sdb1.
  7. Write changes to disk: The changes you've made are still only in memory. To save them to the disk's partition table, type w and press Enter. This will write the changes and exit fdisk.

Here is a summary of the interactive session:

Welcome to fdisk (util-linux 2.37.2).
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 0x54041549.

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-4194303, default 2048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-4194303, default 4194303): +500M

Created a new partition 1 of type 'Linux' and of size 500 MiB.

Command (m for help): p
Disk /dev/sdb: 2 GiB, 2147483648 bytes, 4194304 sectors
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: 0x54041549

Device     Boot Start     End Sectors  Size Id Type
/dev/sdb1        2048 1026047 1024000  500M 83 Linux

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Re-reading the partition table failed.: Invalid argument

The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or partx(8).

After writing the partition table, you may notice a message indicating that the kernel couldn't immediately re-read the partition table. This is normal when working with loop devices. The partprobe command requests that the operating system kernel re-read the partition table.

sudo partprobe

Now, verify that the system recognizes the new partition by running lsblk again.

lsblk /dev/sdb

The output should show the loop device and its new partition. Due to the loop device setup, the partition will appear as loop13p1:

NAME       MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
loop13       7:13   0    2G  0 loop
└─loop13p1 259:0    0  500M  0 part

Since the partition appears as loop13p1 but the lab needs /dev/sdb1 to work, we need to create a symbolic link for the partition. First, let's identify the actual partition device. The pattern p1$ ensures we match only the partition name, not the parent loop device:

PARTITION_DEVICE=$(lsblk -lno NAME /dev/sdb | grep -E "p1$" | head -1)
echo "Partition device: /dev/$PARTITION_DEVICE"

Now create a symbolic link for the partition:

sudo ln -s /dev/$PARTITION_DEVICE /dev/sdb1

Verify that /dev/sdb1 now works:

lsblk /dev/sdb1

The output should now show the partition accessible as /dev/sdb1:

NAME       MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
loop13p1   259:0    0  500M  0 part

You have successfully created a new 500MB Linux partition on /dev/sdb and made it accessible as /dev/sdb1.

Create and Format an ext4 Filesystem with mkfs.ext4

In this step, you will format the new partition you created, /dev/sdb1, with a filesystem. A filesystem provides the structure needed to store and organize files and directories. Without a filesystem, the operating system cannot read from or write to the partition. We will use ext4, which is the default and most widely used filesystem for modern Linux distributions due to its performance, reliability, and features.

The command to create a filesystem is mkfs, which stands for "make filesystem". It's a front-end for various filesystem-specific builders, such as mkfs.ext4, mkfs.xfs, etc. We will use mkfs.ext4 directly. This operation is destructive and will erase any existing data on the partition, which is why it requires sudo privileges.

To format the /dev/sdb1 partition with the ext4 filesystem, execute the following command:

sudo mkfs.ext4 /dev/sdb1

The command will create the filesystem and display information about the process, including the filesystem UUID, block size, and inode count.

mke2fs x.xx.x (xx-xxx-xxxx)
Creating filesystem with 128000 4k blocks and 32000 inodes
Filesystem UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Superblock backups stored on blocks:
 32768, 98304

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

After formatting, you can verify that the filesystem has been created successfully. The blkid command is a great tool for this, as it prints attributes of block devices, including their filesystem type.

sudo blkid /dev/sdb1

The output should clearly show that /dev/sdb1 now has a TYPE of ext4.

/dev/sdb1: UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="1a2b3c4d-01"

For a more detailed view, you can use the dumpe2fs command with the -h flag to display the superblock information. The superblock contains critical metadata about the filesystem.

sudo dumpe2fs -h /dev/sdb1

This command will produce a lot of output. Look for key lines like Filesystem magic number and Filesystem state to confirm the filesystem's integrity.

dumpe2fs x.xx.x (xx-xxx-xxxx)
Filesystem volume name:   <none>
Last mounted on:          <not available>
Filesystem UUID:          xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype extent 64bit flex_bg sparse_super large_file huge_file dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
...

You have now successfully formatted the partition, and it is ready to be mounted and used for storing data.

Mount, Test, and Unmount the Filesystem

In this step, you will learn how to make your newly formatted filesystem accessible to the operating system. This process is called "mounting". Mounting attaches the filesystem on a device (like /dev/sdb1) to a specific directory in the filesystem tree, known as a "mount point". Once mounted, you can interact with the partition just like any other directory.

First, you need to create a mount point. This is simply an empty directory. It's standard practice to create temporary mount points under the /mnt directory. Let's create a directory named /mnt/data. Since /mnt is a system directory, you'll need sudo.

sudo mkdir /mnt/data

Now, use the mount command to attach the /dev/sdb1 partition to the /mnt/data directory.

sudo mount /dev/sdb1 /mnt/data

To verify that the filesystem is mounted, let's first check if the mount command succeeded by checking the mount status. We'll use multiple commands to verify the mount:

## Check if the mount point has the filesystem mounted
mountpoint /mnt/data

If the mount was successful, you should see:

/mnt/data is a mountpoint

Now let's check the disk usage with df. Due to the loop device setup, the partition might appear with its real device name rather than the symbolic link name:

df -h /mnt/data

You should see an entry showing the mounted filesystem:

Filesystem      Size  Used Avail Use% Mounted on
/dev/loop13p1   488M  2.6M  459M   1% /mnt/data

You can also verify with the mount command:

mount | grep /mnt/data

This should show:

/dev/loop13p1 on /mnt/data type ext4 (rw,relatime)

Now, let's test if we can write data to our new filesystem. First, let's check the current ownership and permissions of the mount point:

ls -ld /mnt/data

You should see something like:

drwxr-xr-x 3 root root 4096 Dec 12 10:00 /mnt/data

Now try to create a file in the mount point:

touch /mnt/data/testfile

This command will likely fail with a "Permission denied" error. This is because the mounted filesystem's root directory is owned by the root user. To fix this, change the ownership of the mount point to your current user, labex:

sudo chown labex:labex /mnt/data

Now, try creating the file again:

touch /mnt/data/testfile

This time, the command should succeed. Verify that the file was created:

ls -l /mnt/data

You should see:

total 16
drwx------ 2 root  root  16384 Dec 12 10:00 lost+found
-rw-r--r-- 1 labex labex     0 Dec 12 10:05 testfile

The lost+found directory is a standard feature of ext4 filesystems, used for recovering files in case of filesystem corruption.

When you are finished using the filesystem, you should unmount it using the umount command. It's important to note that you cannot unmount a filesystem if it is currently in use, for example, if your current working directory is inside the mount point. Let's see this in action.

First, change your directory to /mnt/data:

cd /mnt/data

Now, try to unmount it. You can refer to a filesystem by either its device name or its mount point.

sudo umount /mnt/data

You will receive an error message indicating that the target is busy.

umount: /mnt/data: target is busy.

To unmount it successfully, you must first navigate out of the directory. Let's go back to your home directory.

cd ~

Now, run the umount command again.

sudo umount /mnt/data

The command should execute without any output. You can verify that it's no longer mounted by running the mountpoint command:

mountpoint /mnt/data

You should see:

/mnt/data is not a mountpoint

Finally, you can clean up by removing the mount point directory:

sudo rmdir /mnt/data

Troubleshooting Note: If you encounter issues with the mount command not working, you can try mounting using the actual loop device name instead of the symbolic link:

## Find the actual device name
ACTUAL_DEVICE=$(readlink -f /dev/sdb1)
echo "Actual device: $ACTUAL_DEVICE"

## Mount using the actual device name
sudo mkdir /mnt/data
sudo mount $ACTUAL_DEVICE /mnt/data

Configure Persistent Mounting in /etc/fstab

In this step, you will learn how to make your filesystem mount automatically every time the system boots. The mount command you used in the previous step is temporary; the mount will be lost after a reboot. To create a persistent mount, you need to add an entry to a special configuration file called /etc/fstab (filesystem table).

The system reads /etc/fstab during the boot process to determine which filesystems to mount. It's a critical file, so it's always a good idea to create a backup before editing it.

First, let's create a backup of the current fstab file.

sudo cp /etc/fstab /etc/fstab.bak

Next, we need a permanent mount point. In the previous step, we used /mnt/data and then removed it. For permanent mounts, it's common to create a directory in the root filesystem. Let's create a directory named /data.

sudo mkdir /data

While you can use the device name (/dev/sdb1) in /etc/fstab, it's not recommended. Device names can sometimes change between reboots, especially if you add or remove hardware. A much more reliable method is to use the partition's Universally Unique Identifier (UUID), which is a unique string assigned to the filesystem when it was created and does not change.

To find the UUID for /dev/sdb1, use the blkid command again:

sudo blkid /dev/sdb1

The output will show the UUID. Copy this value (without the quotes).

/dev/sdb1: UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="1a2b3c4d-01"

Now, you will edit /etc/fstab using the nano editor. You must use sudo because it's a system file.

sudo nano /etc/fstab

Go to the end of the file and add a new line for your partition. The format for an fstab entry is: <device_identifier> <mount_point> <filesystem_type> <options> <dump> <pass>

Add the following line, replacing xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx with the actual UUID you copied from the blkid command.

UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx /data ext4 defaults 0 2
  • UUID=...: Identifies the partition by its unique ID.
  • /data: The directory where the filesystem will be mounted.
  • ext4: The type of the filesystem.
  • defaults: A standard set of mount options suitable for most cases.
  • 0: The dump field. This is an outdated backup utility flag and should be 0.
  • 2: The pass field. This tells the fsck utility the order for checking filesystems at boot. 1 is for the root filesystem, 2 is for other permanent filesystems, and 0 disables checking.

After adding the line, save the file and exit nano by pressing Ctrl+X, then Y, and then Enter.

Now, instead of rebooting to test, you can use the command mount -a. This command mounts all filesystems listed in /etc/fstab that are not already mounted.

sudo mount -a

If there are no errors, the command will complete silently. You can now verify that your filesystem is mounted correctly using the df command.

df -h | grep /data

The output should confirm that /dev/sdb1 is mounted on /data.

/dev/sdb1       488M  2.6M  459M   1% /data

Your partition will now be mounted automatically every time the system starts.

Create and Manage a Linux Swap Partition

In this step, you will learn about another special type of partition: Linux swap. Swap space is used by the operating system as virtual memory when the physical RAM is full. It allows the system to move inactive pages of memory to the disk, freeing up RAM for active processes. While not a substitute for sufficient RAM, having a swap partition can prevent the system from crashing due to out-of-memory errors.

Important Note: Before creating a new partition, ensure that any existing filesystems on /dev/sdb are unmounted. If the device is currently mounted (from previous steps), you may encounter "Device or resource busy" errors when trying to modify the partition table.

We will create a new partition on /dev/sdb and configure it as swap space. First, let's ensure the device is not mounted, then use fdisk to create the partition. We have already created /dev/sdb1, so this new partition will be /dev/sdb2.

## First, check if the device is mounted and unmount if necessary
lsblk /dev/sdb
sudo umount /data /mnt/data 2> /dev/null || true

## Now create the partition
sudo fdisk /dev/sdb

Inside the fdisk interactive prompt, follow these commands:

  1. Create a new partition: Type n and press Enter.
  2. Choose partition type and number: Accept the defaults for a primary partition (p) and partition number 2 by pressing Enter twice.
  3. Specify sectors: Accept the default first sector. For the size, let's create a 256MB partition. Type +256M and press Enter.
  4. Change partition type: This is the crucial step. Type t to change a partition's type. When prompted for the partition number, enter 2. When asked for the hex code, enter 82, which corresponds to "Linux swap / Solaris".
  5. Print and verify: Type p to review the changes. You should see /dev/sdb2 with its type listed as Linux swap / Solaris.
  6. Write changes: Type w to save the new partition table and exit.
Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (2-4, default 2): 2
First sector (1026048-4194303, default 1026048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (1026048-4194303, default 4194303): +256M

Created a new partition 2 of type 'Linux' and of size 256 MiB.

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'.

Command (m for help): p
Disk /dev/sdb: 2 GiB, 2147483648 bytes, 4194304 sectors
...
Device     Boot   Start     End   Sectors   Size Id Type
/dev/sdb1          2048 1026047   1024000   500M 83 Linux
/dev/sdb2       1026048 1550335    524288   256M 82 Linux swap / Solaris

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

After creating the partition, we need to create a symbolic link for /dev/sdb2 just like we did for /dev/sdb1. First, run partprobe to ensure the kernel recognizes the new partition:

sudo partprobe

Now identify and create the symbolic link for the second partition:

PARTITION2_DEVICE=$(lsblk -lno NAME /dev/sdb | grep p2 | head -1)
sudo ln -s /dev/$PARTITION2_DEVICE /dev/sdb2

Verify the partition is accessible:

lsblk /dev/sdb2

Before formatting the partition as swap space, we need to ensure that the device is not busy. If you encounter a "Device or resource busy" error, it means the device might be mounted. Let's first check and unmount any existing mounts:

## Check current mount status
lsblk /dev/sdb

## If the device is mounted, unmount it
sudo umount /data /mnt/data 2> /dev/null || true

Now that the partition is created and accessible, you need to format it for use as swap space with the mkswap command.

sudo mkswap /dev/sdb2

After formatting, you can activate the swap space. First, check the current swap usage with the free -h command.

free -h

The output will likely show 0B for Swap.

              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       151Mi       1.6Gi       0.0Ki       202Mi       1.7Gi
Swap:            0B          0B          0B

Now, activate the new swap partition using the swapon command.

sudo swapon /dev/sdb2

Check the swap usage again with free -h and swapon -s (summary).

free -h
              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       152Mi       1.4Gi       0.0Ki       202Mi       1.6Gi
Swap:         256Mi          0B       256Mi
swapon -s
Filename    Type  Size Used Priority
/dev/sdb2                               partition 262140 0 -2

You can see the total swap space has increased. To disable a swap partition, use the swapoff command.

sudo swapoff /dev/sdb2

Verify that it has been disabled by running free -h again. The swap space will return to zero. This demonstrates how to dynamically manage swap space on a running system.

Troubleshooting Note: If you encounter "Device or resource busy" errors during this step, it typically means:

  1. The device or one of its partitions is currently mounted
  2. A process is accessing the device

To resolve this, ensure all mount points are unmounted with sudo umount /data /mnt/data before proceeding with partition operations.

Summary

In this lab, you learned the essential skills for managing disk partitions and filesystems on a Linux system. You started by inspecting available block devices using lsblk and then utilized the fdisk utility to create a new primary partition on a secondary disk. Following the partition creation, you formatted it with the ext4 filesystem using mkfs.ext4. You also practiced mounting the new filesystem to a directory, verifying its status, and unmounting it. Finally, you configured persistent mounting by editing the /etc/fstab file with the partition's UUID to ensure it automatically mounts on system boot.

Additionally, the lab covered the process of creating and managing a dedicated swap space. This involved using fdisk again to create a partition and changing its type to "Linux swap". You then prepared this partition as a swap area with the mkswap command and activated it using swapon. To make the swap space persistent across reboots, you also added a corresponding entry to the /etc/fstab file.