Linux: Create a swap file

Harddisk - Morrow Designs DISCUS 10MBRunning out of physical memory? Learn here how to create a swap file on linux.

Baseline

First check the baseline. It is possible that you have some swap already, like a swap partition (a dedicated disk partition only used for swap) or a swap file, like we are creating in this tutorial.

Use the command: ‘swapon -s‘ In the output there is something like this:

Another way to check your memory/swap is using the command ‘free‘. Execute the command: ‘free’ to check there is i.e. no swap at all. See field: Swap: X total -> 0

Remark: The examples to check the baseline are from different systems.

Create swap file

In this example, we will create a swap file of 512 MB.

This will:

  • Create a file of 512 MB, filled with zeros.
  • Set the permissions of the file to read-write for root only. Otherwise other users can peek into the data of other users, stored in (cache) memory.
  • Create a swap file system on the newly created file.

Enable swap

Now it’s time to tell the system that we have a swap file available:

Check result

Check again using ‘swapon -s’

Besides of the original swap partition, we also see a swap file.  Mission accomplished!

Using the ‘free’ command (at the other system) we see:

As you can see at field: Swap: X total,  there is 524284 bytes swap space allocated.