Perhaps you’ve already installed your Ubuntu operating system, and for some reason or the other you forgot swap, or deleted it among other things that may happen. In my case I had it on a different drive which I needed. I simply didn’t want to reformat my installation, and certainly didn’t want to add another drive for a simple swap. Thus, one way to get around this without recreating a swap partion is to create a swap partition “file”. Keep in mind it will do the job just so as long as you don’t end up with a really full disk drive through which the swap file may be created fragmented. Below you’ll find how to accomplish this.
1. Firstly, you must create an empty file, I decided I wanted a 5GB swap file. (1K * 5M = 5GB). You can change the 5 to whatever number of gigs you want to create.
sudo mkdir -v /var/cache/swap
cd /var/cache/swap
sudo dd if=/dev/zero of=swapfile bs=1K count=4M
sudo chmod 600 swapfile
2. Second, we need to convert this newly created file into the swap space file.
sudo mkswap swapfile
3. This file needs to be enabled for paging and swaping by using the following command.
sudo swapon swapfile
Can be verified by using commands:
swapon -s or top
Or grep
top -bn1 | grep -i swap
We can disable swap by using command:
sudo swapoff swapfile
Results should be similar to the image below:
4. We need to make this remain on system by adding it to our fstab file, this enables it to remain upon reboots.
echo “/var/cache/swap/swapfile none swap sw 0 0” | sudo tee -a /etc/fstab
5. Finally, we need to make final checks after reboot. Retest swap file on startup by using the following commands:
sudo swapoff swapfile
sudo swapon -va
or check via the “top” command as in part 3.