You can write to
/proc/sys/vm/drop_caches file to instruct kernel to drop clean caches, as well as reclaimable slab objects like dentries and inodes. Once dropped, their memory becomes free.
This is not recommended to clear memory cache on Linux systems, but it is safe. But clearing cache may cause performance issue with system. Since it discards cached objects from memory, it may cost a significant amount of I/O and CPU to recreate the dropped objects.
This tutorial will help you to clear memory cache on Linux/Unix system via command line.
How to Clear Cache in Linux System
There are three options available to clear cache in Linux system memory. Use one of below as per your requirements.
- Clear PageCache, dentries and inodes in cache memory
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches
- Clear dentries and inodes only in cache memory
sync; echo 2 | sudo tee /proc/sys/vm/drop_caches
- Clear pagecache only in cache memory
sync; echo 31 | sudo tee /proc/sys/vm/drop_caches
sync command is used to increase the number of objects freed by the drop cache. Using this a user can claim more memory by clearing more dirty objects on the system.
How to Schedule Clear Memory Cache
If you have to clear buffer cache regularly, use the cronjob do it. Schedule the following in system crontab to automatically flush cache memory on a regular interval.
Open a terminal and execute ‘crontab -e’ command to edit crontab:
Append below entry to the file:
0 10 * * * sync; echo 3 | sudo tee /proc/sys/vm/drop_caches
The above cron will execute on every hour and flushes the memory cache on your system.
How to find Cache Memory in Linux
Use free command to find out cache memory uses by Linux system. Output of free command is like below
total used free shared buffers cached Mem: 16050 15908 142 0 120
12953-/+ buffers/cache: 834 15216 Swap: 0 0 0
Here the last column is showing cached memory (12953 MB) on Linux system. The -m option is used to show output MB’s.