Adding a swap memory to Linux from command line in 6 steps

Generate a file and save it in fstab

Published:
Last modified:

Overview

This is a quick guide to add a swap file to Linux from command line.

But first, what is swap memory?

Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.

We will add a special formatted file that works as a swap file and then add it to the /etc/fstab to have it also after the system reboots.

Steps

1. Create File

Create a file of 4GB

sudo fallocate -l 4g /4GiB.swap

or if fallocate isn’t present:

sudo dd if=/dev/zero of=/4GiB.swap bs=1024 count=4000

2. Readonly

Make it readable only for root sudo chmod 600 /4GiB.swap

3. Swap format

Format the file as swap: sudo mkswap /4GiB.swap

4. Activate it

Enable use of Swap File sudo swapon /4GiB.swap

4.1 Verify

Verify it is active.


$ cat /proc/swaps
Filename                                Type            Size    Used    Priority
/4GiB.swap                              file            4194300 0       -2

5. Save

Make the file present after rebooting the system. To make it permanent, add it to /etc/fstab.

echo ‘/4GiB.swap none swap sw 0 0’ | sudo tee -a /etc/fstab

5.1 Verify


$ cat /etc/fstab 
LABEL=cloudimg-rootfs   /        ext4   defaults        0 0
LABEL=UEFI      /boot/efi       vfat    defaults        0 0
/4GiB.swap none swap sw 0 0

Conclusion

Now we have our RAM memory and can also paginate into swap memory.


$ free -m
              total        used        free      shared  buff/cache   available
Mem:            981         819          70           3          91          40
Swap:          4095           3        4092

References

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


How to add a swap file to Ubuntu Linux from command line by generating a special file and configuring it in fstab.

Clutter-free software concepts.
Translations English Español

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·