How to create swap space on Linux by adding a swap file?

When the physical memory of a system is full, the operating system moves inactive pages of physical memory to the swap space. This is useful for the systems that have a small amount of physical memory.

The swap space should not be considered as the replacement of physical memory. As it is located on the hard disk it has slower access time than physical memory.

The swap space or swap area can be a dedicated swap partition, a swap file, or a combination of both. If swap partition is not present in your system then you can create the swap space by creating a swap file.

How to add the swap file

We will use the dd command to create a swap file on a system. First, you need to determine the size of the swap file in block size, you can simply find the block size by multiplying the size of the swap file in megabyte to 1024 for example the swap file of size 2048 MB will have the block size 2048*1024 =2097152.

Now use the following command to create the file –

dd if=/dev/zero of=/swapfile bs=1024 count=2097152

The file is now created with the name of the swapfile

The users with root privilege will be able to read or write the swapfile, now use the following command to provide the correct permissions to this file –

chmod 0600 /swapfile

Now use the following command to set up this file as the swap space –

mkswap /swapfile

Enable the swap space by using –

swapon /swapfile

To enable the swap space permanently append the given line into /etc/fstab

/swapfile     swap   swap   defaults 0 0

Verify swap space

After adding and enabling the swap file you can verify the swap space on your system by using the following command –

cat /proc/swaps

or by using –

free -h

How to remove the swap file

For any reason, if you decided not to use this swap space and want to remove this file then you can remove it by using the given commands.

First, deactivate the swap space by using –

swapoff -v /swapfile

Then remove the swapfile entry from /etc/fstab file which was –

/swapfile     swap   swap   defaults 0 0

And then use the rm command to remove this file from the system –

rm /swapfile

Now you have successfully deleted the swapfile from your system.


The swap space is generally implemented with swapfile in systems running on virtual machines. Now if you have a query on this topic then you can leave it in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version