Adding a new swap file. How to edit fstab to enable swap after reboot?

I've deleted my existing swap partition due to some partitioning problem. I don't have a swap space now so I've created a swap file with:

dd if=/dev/zero of=/root/myswapfile bs=1M count=1024 

Here's after swapon -s:

/root/myswapfile file 1048572 1320 -1 

Now I want to edit my /etc/fstab to enable the swap file after reboot.

2

1 Answer

These ares the steps to create a swap on a file:

Create a large file e.g. with

sudo mkdir -p /var/cache/swap/ # create a directory that holds the swap file sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096 # for 4 GByte 

Of course any other method of creating a file of defined size would do.

Announce swap to the system

sudo chmod 0600 /var/cache/swap/myswap # only root should have access sudo mkswap /var/cache/swap/myswap # format as swap sudo swapon /var/cache/swap/myswap # announce to system 

Insert the following line in /etc/fstab for swap from the next boot:

/var/cache/swap/myswap none swap sw 0 0 

Note: In case you have your system files on a SSD you may want to consider to hold your swap file on a hard disk location.

Also note: You can not use a swap file for hibernation (see Ubuntu SwapFaq)

Additional note for Ubuntu >= 17.04: A swap on file /swapfile is created by default in a new installation (when no swap partition was present). We can manually create a swap partition later if we prefer.

In case we want to replace an existing swap (e.g. partition) with another swap (e.g. on file) we need to remove the old swap with

sudo swapoff -a # for all 

Then remove the swap entry from /etc/fstab or replace it with the new swap respectively.

10

You Might Also Like