How to Add Swap Space on Ubuntu 20.04


A swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.

In the case of Linux, the swap file is an important part. It's not a must-have option but having one is crucial for a number of purposes. Generally, when installing the system, you have to declare the size of the swap file. The recommended size is 4GB but you can either decrease or increase it depending on your demand.

If you want to change the size of your swap file just follow the following steps.

Note:  Running all these commands requires root privilege, so I recommend running a root terminal.

  1. Turn off all running swap processes
swapoff -a
  1. Resize swap
fallocate -l 2G /swapfile

Here, the total size of the swap file will be 2GB .

  1. CHMOD swap
chmod 600 /swapfile
  1. Make file usable as swap
mkswap /swapfile

Activate the swap file

swapon /swapfile

To verify your swap size run the following command and you will see the swap size.

free -m

Removing a Swap File

To deactivate and remove the swap file, follow these steps:

Start by deactivating the swap space by typing:

sudo swapoff -v /swapfile

Next, remove the swap file entry  /swapfile swap swap defaults 0 0 from the  /etc/fstab file.

Finally, remove the actual swapfile file using the  rm command:

sudo rm /swapfile

Thank you for reading this blog.

21