Swap - How to create a swap file

Sep 5, 2015

The swap file is used to “expand” the memory RAM, so increases the capability to execute more software at the same time. In a GNU/Linux, it’s possible to create a dedicated swap partition or use a file.

Below I’ll show step by step how to create a Swap file in a Linux OS.

With this feature activated, will be possible to run many applications and keep the unactive process in “stand-by” in HD or SSD while you can play any heavy game or execute an HTTP or FTP service.

Simple script:

You can use the script below or check the following steps with the proper explanation:

# Make sure you're running as "root"
# run "sudo su" first

# Set the amount of swap memory you want
# (in Gigabytes)
export SWAP_SIZE_GB=2

# Create swap file and set permissions for root user only
dd if=/dev/zero of=/swap bs=${SWAP_SIZE_GB}M count=1024
chmod 600 /swap
mkswap -f /swap

# Add to fstab to always mount during booting
echo '/swap none swap sw 0 0' >> /etc/fstab

# Turn on all swap from fstab
# (you'll need to restart your PC if this don't work)
swapon -a

# Check if you swap turned on
free -mh

Step by step

Become super user:

# Ubuntu
sudo su

# Debian (without sudo)
su -

Create the swap file

Create an empty file from "zeros". The /dev/zero is a special Linux file with infinity size made entirely by zeros:

# Copy 1M*1024 (1GB) of zeros to /swap
dd if=/dev/zero of=/swap bs=1M count=1024

Set permissions to limit access to the swap file exclusively to root user:

chmod 600 /swap

Convert the empty file to a swap file:

mkswap -f /swap

Add swap configuration to “/etc/fstab”. Modify the file with something like this:

nano /etc/fstab
swap-configuration

First, restart your machine, then run the following command:

# Check free memory
free -h

If you get a result like the one below, that means everything worked ok!

swap-check

If you have any questions, just leave a comment below!

See ya! 😉

Tags

Luiz Costa

I am a senior software engineer at Red Hat / Ansible. I love automation tools, games, and coffee. I am also an active contributor to open-source projects on GitHub.