Linux : How to create swap area on a live system

By | February 16, 2013

This article is about how to create swap space on a live RHEL/CentOS Linux system. However you can still follow that procedure in case you messed up your filesystem and swap is now non-existent (e.g.: swap show 0M).

First, use fdisk to edit the partition table and create a partition (this step might be skipped if you already have one) :

fdisk /dev/sda

Useful fdisk commands are :

m = help
p = show the partition layout
n = create a partition
t = change partition type
w = write changes
q = quit fdisk utility

Then, show your current partition layout (hit “p” key) :

Device Boot Start End Blocks Id System
/dev/sda1 *   1     32 256000 83 Linux
/dev/sda2 32  424   3145728   83 Linux
/dev/sda3 424 45168 359403520 83 Linux

(We can see we have no swap area here!)

Let’s create a partition (hit “n” key) :

Command action
e extended
p primary partition (1-4)

(Select extended or primary depending on your situation. We’ll use extended here)

Device Boot Start End Blocks Id System
/dev/sda1 * 1   32    256000    83 Linux
/dev/sda2 32    424   3145728   83 Linux
/dev/sda3 424   45168 359403520 83 Linux
/dev/sda4 45168 45689 4190620+  5 Extended
/dev/sda5 45168 45689 4190589   83 Linux

Change the type of your brand new partition for swap use (hit “t” key and enter “82” as hex code) :

Command (m for help): t
Partition number (1-5): 5
Hex code (type L to list codes): 82
Changed system type of partition 5 to 82 (Linux swap / Solaris)

Now write the changes to the partition table (hit “w” key and then “q”).

We are now ready to format the partition as swap, use “mkswap” command :

mkswap /dev/sda5

Will return :

# mkswap /dev/sda5
Setting up swapspace version 1, size = 4190584 KiB
no label, UUID=d52c8bdb-96a8-4244-a300-b753b08570d6

The last step is to set (or modify if the swap where accidental removed) the partition UUID in fstab :

vi /etc/fstab

Config line shoud looks like :

UUID=d52c8bdb-96a8-4244-a300-b753b08570d6 swap                    swap    defaults        0 0

Final step, enable the swap!

swapon -a