Linux: Decrease swap file size

The swap file must be initialized to zeros. However, if the swap file already exists and is initialized, all you need to do is truncate it.

First, turn off swap.

sudo swapoff /swapfile

Then, truncate the file to the correct size.

sudo truncate --size=16G /swapfile

or delete it and create a new file of zeros.

sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1GiB count=32
sudo chmod 600 /swapfile

Setup swap area.

sudo mkswap /swapfile

Restart swapping.

sudo swapon /swapfile

[Note: Your swapfile may be somewhere else. swapon will find it.]

4 / 2021