When working with Linux, it can be crucial to understand how to manage and optimize the system’s swap space. Swap space is a part of the hard drive where Linux stores data that does not fit into physical RAM. When running low on RAM, Linux will move some unused portion of the memory into the swap space thereby freeing the RAM for more critical applications. However, continually writing to the hard drive can slow down your system, so it’s beneficial to free up swap space when it’s no longer necessary.
In this tutorial, we will learn how to free swap space in Linux. This process requires root or sudo privileges, so ensure you have the necessary permissions before proceeding.
Checking the Swap Space
Firstly, let’s check how much swap space is currently being used. The command to do this is free -h. This will display the total, used, and free amounts of physical and swap memory in the system, in human-readable format (i.e., auto-selecting the appropriate unit for each size).
$ free -h
Turning off the Swap
Once we’ve checked the swap usage, the next step is to turn off the swap with the swapoff command. This command makes the swapped out pages of a specified swap area no longer available for swapping in.
$ sudo swapoff -a
Note: The -a option disables all swap areas. If you want to disable a specific swap area, replace -a with the path of the swap area.
Clearing the Swap Cache
After turning off the swap, we can clear the swap cache. The sync command is used for this. It flushes the filesystem buffers to the disk, ensuring that all cached data is stored before we turn the swap back on.
$ sudo sync
Turning the Swap Back On
Finally, we can turn the swap back on with the swapon command. This will enable all swap areas again, with a newly freed cache.
$ sudo swapon -a
Note: The -a option enables all swap areas. If you want to enable a specific swap area, replace -a with the path of the swap area.
And that’s it! You have successfully freed swap space on your Linux system. Regularly checking and managing your swap space will help you maintain a healthy and high-performing Linux system.