Add swap space to Linux

This is an old sysadmin trick, but a good one all the same.
Suppose that you finished installing a brand-new Debian GNU/Linux server, and for whatever reason you forgot to set aside some space for a swap partition. Or you correctly got some swap space at installation time but now you desperately need some more. Well, despair not. It’s a little known fact that you can have swap space in a file on top of the filesystem instead of using a dedicated block device.
This simple recipe will give you 2Gb of swap space. Here we go:

# mkdir /var/swap
# chown root.root /var/swap
# chmod 700 /var/swap
# dd if=/dev/zero of=/var/swap/01.swp bs=1024 count=2M
# chown root.root /var/swap/01.swp
# chmod 600 /var/swap
# mkswap /var/swap/01.swp

Now add this newly created swap space to your /etc/fstab:

/var/swap/01.swp       none    swap    sw              0 0

Teoretically, you won’t get the same performance as using a dedicated block device, and if the file actually gets fragmented it might drop rigt to the floor, so if you try this at all do it as soon as possible after installation. So if what you’re trying to do is to *increase* your available swap space instead, you may add a priority option to give preference to the block-device swap space:

/dev/hda1              none    swap    sw,pri=1              0 0
/var/swap/01.swp       none    swap    sw,pri=2              0 0

And just this time activate the swapspace with addswap (The initscripts will do it on every boot thereafter):

# swapon -av

That’s all there is to it. I particularily like how newer BOFH generations look at this with some skepticism at first, and with endless amazement later.

[tags]Debian, GNU, Linux, swap, sysadmin[/tags]