Add more swap space in Linux without any unpartitioned space

Q I need to add more swap space to my Linux machine but I don't have any unpartitioned disk space. Is there anything I can do?

A GNU/Linux is a lot more flexible than other operating systems in a lot of respects, including swap space. First off, work out how much additional swap space you need. For argument's sake, let's say you want another 1GB of swap. Next, identify a partition on your system that has at least that amount of space free and won't be needed any time soon. When I built my system, for example, I built it with a 4GB /opt partition which had only 1.5GB utilised. Then it's time to create the file you are going to use for swap. To do this you need to use the dd command, which takes various arguments including a block size argument and a count argument. To create a file 1GB in size, use the following command:

dd if=/dev/zero of=/opt/swapfile bs=1G count=1

This command will write a 1GB file at /opt/swapfile. The if switch specifies the input source while the of switch specifies the output file. Next up you need to format it as a swap file:

mkswap /opt/swapfile

Once this has been set up as a swap file you need to activate it by executing

swapon /opt/swapfile

You should be able to see it active on the system by executing cat /proc/swaps or simply free at the command line. To enable the swap during the boot process, add it to your /etc/fstab file:

/opt/swap   swap  defaults 00

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar