Partitioning Disks and Creating Swap Space in Linux

Partitioning Disks in Linux

In Linux, we can use various command-line tools for partitioning disks. One such tool, capable of handling both MBR and GPT partitioning, is parted. We’ll primarily focus on its interactive mode.

Identifying Connected Disks

Before partitioning, let’s list the disks connected to our computer. We can do this using the parted command in command-line mode:

sudo parted -l

This command displays information about connected disks, including their size and partition tables. For instance, /dev/sda might represent a 128GB hard drive, while /dev/sdb could be an 8GB USB drive.

Understanding parted -l Output

The output of parted -l provides details about each disk’s partition table, such as GPT or MBR. It also shows the number of partitions, their starting and ending points on the disk, sizes, file systems, names, and associated flags.

Interactive Partitioning with parted

Let’s partition the USB drive (/dev/sdb). We’ll use the interactive mode of parted:

sudo parted /dev/sdb

Now we’re inside the parted tool. To exit, use the quit command.

Setting a Disk Label

Before creating partitions, we need to set a disk label. Since we’ll be using the GPT partition table, we’ll use the following command:

mklabel gpt

Creating Partitions

To create partitions, we’ll use the mkpart command. Let’s create a 5GB partition:

mkpart primary 1MiB 5GiB

We use primary as the partition type (relevant for MBR, but we’ll use it here for consistency). The start point is 1MiB (1 mebibyte), and the endpoint is 5GiB (5 gibibytes).

Note on Data Measurement

When working with storage, it’s crucial to use precise data measurements. We use mebibytes (MiB) and gibibytes (GiB) to avoid confusion between kibibytes (KiB) and kilobytes (KB), as they represent slightly different values.

Formatting the Partition

After creating the partition, we need to format it with a file system. We’ll use ext4 in this example:

sudo mkfs.ext4 /dev/sdb1

Creating Swap Space

Swap space in Linux is used for virtual memory. We can create a swap partition on the remaining space of our USB drive:

mkpart primary linux-swap 5GiB 100%

This command creates a swap partition starting from 5GiB and extending to the end of the disk (100%).

Making the Partition a Swap Space

To designate the partition as swap space, we’ll use the mkswap command:

sudo mkswap /dev/sdb2

Enabling Swap Space

Finally, we need to enable the swap space using the swapon command:

sudo swapon /dev/sdb2

Automounting Swap Space

To automatically mount the swap space at boot time, add an entry to the /etc/fstab file.

Conclusion

We’ve successfully partitioned a disk and created swap space in Linux. Remember to exercise caution when using partitioning tools, as modifying the wrong disk can lead to data loss.