Adding swap after installation

by Bryanpwo edited by joekamprad (12.8.2020) + (24.02.2021)

To add after installation there are two options:

1. creating a swap partition by shrinking space and adding a partition using Gparted on the Live ISO

2. creating a swap file.

Just a note, it’s not recommended to make a swap partition on an SSD, this can damage the medium.

Making a swap partition with Gparted

Boot your machine with the Live ISO and open Gparted. Select the last partition on your HDD (this can either be the Root partition or the Home partition, depending on how you partitioned your disk) and shrink the partition by leaving a disk space free equal to the size of your RAM or double the size, that’s up to you. Then select the free space and mark it as a swap partition, let Gparted do its work, and boot back into your installed system and swap should be recognized by systemd. To check enter:

swapon --show

Making a swap file

The above method is the easiest one, but it can damage the partition that you’ve shrunk. So you can also make a swap file.

Commands like cp(1) or truncate(1) create files with holes. These files will be rejected by swapon.

Preallocated files created by fallocate(1) may be interpreted as files with holes too depending of the filesystem.

As documented here: swapon.8#Files_with_holes

So as Archwiki recommends better use dd command with some danger of using a Destroyer of Disks.

!! This following step is only needed if you run on Btrfs filesystem !!

Notes if you are using Btrfs

For Btrfs, first create a zero-length file, set the No_COW attribute on it with chattr, and make sure compression is disabled. This is not needed on other filesystems (like ext4) !!

sudo truncate -s 0 /swapfile
sudo chattr +C /swapfile
sudo btrfs property set /swapfile compression none

If you are using a subvol for swap like current default BTRFS installs will do your swapfile location needs to be changed to /swap/swapfile instead of /swapfile.

Further for all file systems:

Use dd to create a swap file the size of your choosing. For example, creating a 512 MiB swap file (for all filesystems)

sudo dd if=/dev/zero of=/swapfile bs=1M count=512 status=progress

Replace count=512 with the amount of MB you want to install for swap use. then:

sudo chmod 600 /swapfile

To give the swap file root-only permissions.

sudo mkswap /swapfile

To make the file as swap space and finally to enable the file:

sudo swapon /swapfile

Edit the fstab configuration to add an entry for the swap file:

/etc/fstab

/swapfile none swap defaults 0 0

Note: The swap file must be specified by its location on the file system, not by its UUID or LABEL.

to check:

swapon --show

Remove swap file:

To remove a swap file, it must be turned off first and then can be removed:

sudo swapoff /swapfile
sudo rm -f /swapfile

Finally, remove the relevant entry from /etc/fstab.

Connect with us:

Adding swap after installation

  • by