How to create a Linux swap file

fluffyc3rb3rus
3 min readJan 4, 2022
Linux Swap Files

When you first installed your Linux distribution, you forgot to create a properly sized swap partition. Someone could be panicked, since resizing a partition under some conditions can be very difficult, but in our help comes the swap file.

It’s very simple to create a swap file, with a couple of shell commands you will be out of troubles. First of all, we check our swap status.

free -h

Checking the swap status

As we can see, we have only 974Mi allocated to swap. We want to allocate the swap file under the root of our file system, in a file called “swapfile”, and we desire that the file size will be 4G.

sudo fallocate -l 4G /swapfile

Allocating the swapfile

Now we need to properly set the permissions for the swapfile.

sudo chmod 600 /swapfile

Giving the swapfile the right permissions

Then, we use the mkswap command to set up a swap file in our desired path.

sudo mkswap /swapfile

Declaring that the created file is a swap file

The swap file is ready to be used. To activate the swap, we need to use swapon.

sudo swapon /swapfile

Activating the swap

Checking again our swap status, we can see that the size changed from 974Mi to 5Gi. If we want to make the change permanent, we must edit the fstab file.

Memory and swap status

I’m using nano to edit the /etc/fstab file, but feel free to use the text editor of your choice.

sudo nano /etc/fstab

Now, add the following line to the file:

/swapfile none swap sw 0 0

Content of the /etc/fstab file
Content of the /etc/fstab file

If you are using nano, save the file using CTRL+O, exit and…the magic is done! :)

--

--

fluffyc3rb3rus

Penetration Tester, traveller and food addicted, but still human. I love security, Linux, games :) | eMAPT| eWPT | OSCP | CTF Player