Tips

How to Clear Swap Memory in Linux

Learn how to clear swap in Linux without losing any important data. Also learn why would you clear the swap manually.

Abhishek Prakash
Abhishek Prakash

Swap is a virtual memory concept that allows your system to use a portion of your hard drive as the physical memory (RAM). Your system swaps the inactive pages in memory in RAM to this swap space on the hard disk. This way, your system has more free RAM available for other programs.

I have shown you to check RAM in Linux and I have also discussed how to check swap usage on Linux. In this quick tip, I’ll show you how to clear swap memory in Linux.

How to Check Swap Space in Linux
Wondering how much swap your system has and how much swap is in use? Here’s how to check swap usage in Linux.

Clear swap in Linux

But first, why would you want to clear swap at all? There could be various reasons. Some time your system will use a lot of swap even when plenty of RAM is available.

This may or may not be associated with swappiness of your system. Sometimes it happens that the RAM doesn’t swap back the pages from swap space to RAM. In such cases, you’ll have to manually clear the swap.

Attention

Before clearing the swap, check that you have enough free RAM available to take all the pages from swap. In other words, you should have more free RAM available than the current swap in use.

You can see the state of RAM and swap using the free command in Linux:

free -h
              total        used        free      shared  buff/cache   available
Mem:           7.5G        5.4G        211M        916M        1.9G        953M
Swap:           14G        1.7G         13G

Once you are sure that the size of free RAM is bigger than the swap memory in use, you can clear the swap memory by turning it off and on again.

Pun aside, that’s the way to do it. Disable all the swap using this command:

swapoff -a

Now turn the swap back on:

swapon -a

That’s it. This simple exercise will clear the swap in your Linux system. I hope you find this little tip helpful. Any questions or suggestions are always welcome.



Join the conversation.