Detailed Notes on Swap Partitions in Linux

Overview of Swap Partitions

  • Definition of Swap:

    • Swap is RAM that is emulated on disk, allowing for the extension of memory resources.

    • Particularly beneficial for Linux systems, as it allows the operating system to move inactive application memory to swap, effectively freeing up RAM for active tasks.

  • Importance of Swap:

    • All Linux systems should have at least some amount of swap space unless there are specific reasons not to.

    • Swap can be created on any block device, and it is also possible to utilize swap files.

Configuring Swap Partitions

  • Creating a Swap Partition:

    • To configure a partition as swap:

    • Set the partition type to "Linux swap".

    • After creating the partition, use the command mkswap to create a swap file system.

    • Finally, activate the swap using the command swapon.

Practical Example: Creating a Swap Partition

  • Steps to Create and Activate a Swap Partition:

    1. Open Terminal: Begin by accessing a terminal.

    2. Using fdisk:

    • Command: fdisk /dev/nvme0n1

    • Note: Confirming device names can be done using the command lsblk.

    1. Create a New Partition:

    • Use the command n to create a new partition.

    • First Sector: Press enter to accept the default.

    • Last Sector: Specify the size of the swap by entering +1G to allocate one gigabyte.

    1. Change Partition Type:

    • Use command p to view current partition types; by default, it may show Linux file system.

    • Command t is used to change the partition type for the newly created partition (e.g., t <partition number>).

    • Set the type to swap:

      • You may use command l to list available partition types if needed.

    • Verify the type is set correctly with command p again.

    1. Write Changes:

    • Write the partition changes using command w.

Setting Up the Swap File System

  • Command to create the swap file system:

    • mkswap /dev/nvme0n1p5

  • Mounting the Swap Partition:

    • Since entries should be added to /etc/fstab for automatic activation on boot:

    • Copy the UUID of the swap partition using the command blkid.

    • Use command line redirection to append it to the /etc/fstab file.

    • Example entry format:

    • UUID=<uuid> none swap defaults 0 0

    • Mounting Swap:

      • Use the command swapon -a to activate the swap space.

      • Verify swap space with command free -m, which shows the current swap size (should display total swap, e.g., 3 GB).

Conclusion

  • By following these steps, a block device can be added to the swap space in a Linux system, allowing for better memory management and enhancement of overall system performance.