Table of Contents

Create/Remove/Resize Swap Space without Modifying Partitions on Linux

Cyrus Kao
Last modified on .

When a Linux machine runs out of physical memory (a.k.a random-access memory - RAM), the swap space will be used instead. It literally swaps data from your RAM to your disk space to free up memory. In some perspectives, it even speeds up your CPU too, since when the less the memory is free, more time the CPU spend on GC (Garbage Collection).

There is an equivalent of swap space on Windows called page file.

There are two ways to configure swap space on Linux, either by creating a swap partition or a swap file. The former is usually done on system installation. The latter creates a swap file on the existing file system. You can even vary its size on-the-fly or disable it anytime you wish.

Check for Existing Swap Space

Some Linux distros' installations like Debian/Ubuntu might come with swap enabled by default. To check the swap and RAM size in MiB:

$ free -m
               total        used        free      shared  buff/cache   available
Mem:            7820        3186        1160        1098        3474        3223
Swap:              0           0           0

Create Swap Space

We'll be creating a swap file instead of a swap partition. This is a more flexible way to manage swap. Also, more beginner-friendly since no low-level operations that might cause catastrophe are included.

Deciding Swap Size

Here is a simple guideline to help you decide how much swap space you need according to your RAM capacity:

RAM Swap
RAM <= 2 GB 2 x RAM
2 GB < RAM < 8 GB 1 x RAM
RAM >= 8 GB 8 GB

Create Swap File

Create a swap file with your desired size (in my case, it is 7820 MiB):

$ sudo dd if=/dev/zero of=/swap bs=1M count=7820
7820+0 records in
7820+0 records out
8199864320 bytes (8.2 GB, 7.6 GiB) copied, 16.5793 s, 495 MB/s

Set the permissions to 600 (only the owner is allowed read and write) for security:

$ sudo chmod 600 /swap

Format the file to swap:

$ sudo mkswap /swap
Setting up swapspace version 1, size = 7.6 GiB (8199860224 bytes)
no label, UUID=04d5ffd9-0535-4077-ac54-f095f108c1a3

Activate the swap space:

$ sudo swapon /swap

Now the swap is on:

Screenshot of htop

Enable Swap at System Startup

To enable swap at system startup, edit the file systems table (fstab) configuration file (/etc/fstab) to add the following line, then save:

/etc/fstab/swap	none	swap	defaults	0 0
Plain text

Remove Swap Space

Turn off swap then remove the swap file:

$ sudo swapoff /swap
$ sudo rm /swap

And remember to delete the line added to /etc/fstab in Enable Swap at System Startup.

Resize Swap Size

Just repeat the processes of Remove Swap Space and Create Swap Space.


Sign in to leave a comment.