83.2 Swap File Creation

20220822

To add, for example 4GB, to the swap space we can create a new file of that size and tell the operating system to use this as swap.

First, check the amount of storage space available using df:

df -h
Filesystem                 Size  Used Avail Use% Mounted on
tmpfs                      1.6G  3.2M  1.6G   1% /run
/dev/mapper/vgubuntu-root  467G  417G   26G  95% /
...

We’ll create the new swap file in root (/) using fallocate and then ensure it is not generally available to users to view using chmod, boith commands requiring administrator access using sudo:

sudo fallocate --length 4G /swapfile
sudo chmod 600 /swapfile

To set up the new file as a special swapfile we use mkswap:

sudo mkswap /swapfile
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=a1a0d080-e4bd-4cd8-ab09-0bb9c4eaf9e0

Now tell the operating system to use the file for swap with the swapon command:

sudo swapon /swapfile

Check it is recognised:

sudo swapon --show
NAME      TYPE      SIZE   USED PRIO
/dev/dm-2 partition 980M 456.2M   -2
/swapfile file        4G     0B   -3

Next, make sure the swap is used after a reboot of the computer by adding a line to /etc/fstab that results in swapon -a to add the new swapfile to swap space:

sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

If you wanted to remove the swap file from usage simply use swapoff:

sudo swapoff /swapfile

You could then remove /swapfile using rm and recreate it as described above, making it larger or smaller if you wanted. If you remove it permanently then be sure to remove the entry from /etc/fstab.



Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0