Home / Linux / How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

Like any other operating system, Linux has implemented a memory management efficiently and even more than that. But if any process is eating away your memory and you want to clear it, Linux provides a way to flush or clear ram cache.

How to Clear Cache in Linux?

Every Linux System has three options to clear cache without interrupting any processes or services.

1. Clear PageCache only.

2. Clear inodes and dentries .

3. Clear PageCache, dentries and inodes.

 

Moreover, it will also slow the system for a few seconds while the cache is cleaned and every resource required by OS has loaded again in the disk-cache.

Now we will be creating a shell script to auto clear RAM cache daily at 2 am via a cron scheduler task. Create a shell script cache.sh and add the following lines.

Set execute permission on the ccache.sh file.

Now you may call the script whenever you required clearing ram cache.

Now set a cron to clear RAM cache every day at 2 am. Open crontab for editing.

Append the below line, save and exit to run it at 2 am daily.

For more details on how to cron a job, you may like to check our article on 11 Cron Scheduling Jobs.

Is it a good idea to auto clear RAM cache on a production server?

No! it is not. Think of a situation when you have scheduled the script to clear ram cache every day at 2 am. Every day at 2 am the script is executed and it flushes your RAM cache. One day for whatsoever reason may be more than expected users are online on your website and seeking resource from your server.

At the same time, scheduled script to run and clears everything in cache. Now all the user are fetching data from disk. It will result in a server crash and corrupt the database. So clear ram-cache only when required, and known your footsteps, else you are a Cargo Cult System Administrator.

How to Clear Swap Space in Linux?

If you want to clear Swap space, you may like to run the below command.

Also, you may add above command to a corn script above, after understanding all the associated risk.

Now we will be combining both above commands into one single command to make a proper script to clear RAM Cache and Swap Space.

After testing both above command, we will run command “free -h” before and after running the script and will check the cache.

BCS Exam Preparation
BCS Exam Preparation
* মোট প্রশ্ন ১৬৭৭১
* প্রত্যক বিষয় টপিক অনুযায়ী সাজানো
* অংক এবং ইংলিশ এর প্রত্যকটি প্রশ্ন ব্যাখ্যাসহ
* আগের পরীক্ষার প্রশ্ন গুলো সমাধান করা
GET UPDATE INSTANTLY
Increase your knowledge!
Your Information will never be shared with any third party.
BCS Exam Preparation
BCS Exam Preparation
* মোট প্রশ্ন ১৬৭৭১
* প্রত্যক বিষয় টপিক অনুযায়ী সাজানো
* অংক এবং ইংলিশ এর প্রত্যকটি প্রশ্ন ব্যাখ্যাসহ
* আগের পরীক্ষার প্রশ্ন গুলো সমাধান করা