Set up a Linux swap area
The mkswap command is used to set up a Linux swap area on a device or in a file. After creating the swap area, use the swapon command to start using it. While an optional parameter allows specifying the swap area size, it is provided for backward compatibility and is usually unnecessary, as the command defaults to using the entire device or file.
mkswap [OPTION]... DEVICE [SIZE]
-c:Check for bad blocks before creating the swap area.
-f:Force execution. Required when creating a swap area on SPARC machines.
-v0:Create an old-style swap area (default).
-v1:Create a new-style swap area.
Device: The device file or regular file to be used as swap space.
Check system swap space size:
free -m
View current swap space (files/partitions):
swapon -s
# or
cat /proc/swaps
Add swap space
You can add a swap partition or a swap file. A partition is generally recommended, but a file is useful if you have limited free space.
Steps to add a swap partition:
fdisk to create a partition (e.g., /dev/sdb2).mkswap /dev/sdb2
swapon /dev/sdb2
/etc/fstab to enable it at boot:/dev/sdb2 swap swap defaults 0 0
Steps to add a swap file:
dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
mkswap /swapfile1
swapon /swapfile1
/etc/fstab:/swapfile1 swap swap defaults 0 0
After adding and enabling the swap space, verify it using free -m or cat /proc/swaps.
Remove swap space:
swapoff /dev/sdb2
/etc/fstab.fdisk or other tools to delete the partition or rm to delete the swap file.