How to Clear RAM Memory Cache, Buffer and Swap Space on Linux
In this article, we will see How to Clear RAM Memory Cache, Buffer, and Swap Space on Linux. In every system we do come across caches that have unwanted files and can harm our system, the same thing happens in Linux cache and if you want to clear the cache and free some memory then Linux has many commands to do that.
To Clear Cache in Linux:
In all the Linux systems we have three options to clear cache without interrupting any services or processes.
Example 1: To Clear PageCache only
Syntax :
sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches'
The command # free -h will give us the status of the memory
drop_caches is used a clean cache without killing any application, you can run the # free -h command to see the difference between used and free memory before and after clearing the cache
Example 2: To Clear dentries and inodes
Syntax:
sudo sh -c 'echo 2 > /proc/sys/vm/drop_caches'
Example 3: To Clear PageCache, dentries and inodes
Syntax:
sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
Now using Linux Kernel, to free Buffer and Cache in Linux we will Create a shell script to auto clear RAM cache daily, through a cron scheduler task., the command vim script.sh is used to create a shell script “script.sh”
Now in script, you have to add the below syntax:
echo " echo 3 > /proc/sys/vm/drop_caches"
Now to set run permission, to clear ram cache, you have to call the script whenever required, setting a cron to clear RAM caches every day for 3 hours.
# chmod 755 script.sh # crontab -e
Example 4: To Clear Swap Space in Linux
You can clear the swap space by running the below command
Syntax :
sudo swapoff -a sudo swapon -a
You can run the # free -h command to see the difference between used and free memory before and after clearing the swap space
Add the above command to a cron script, Here we are going to combine this two different command into one single command, to form a proper script which will help us to clear Swap Space and RAM Cache.
echo 3 > /proc/sys/vm/drop_caches & & swapoff -a & & swapon -a & & printf ‘\n%s\n’ ‘ ‘ Ram-cache and the swap get cleared’
Now Ram cache and swap will be cleared you can run # free -h command to see
After running the command you will get output like this
Please Login to comment...