Linux system has efficient memory management. But sometimes, there may be a bug in one of the applications or scripts causing them to consume too much memory. This can slow down your system and affect its performance. In such cases, it is advisable to clear RAM cache memory. In this article, we will look at how to clear cache memory in Linux.
How to Clear Cache Memory in Linux
Here are the steps to clear cache memory in Linux. Every Linux system supports 3 commands to help you clear cache memory without interrupting any process or tasks.
Here is the command to clear PageCache only
# sync; echo 1 > /proc/sys/vm/drop_caches
Here is the command to clear dentries and inodes.
# sync; echo 2 > /proc/sys/vm/drop_caches
Here is the command to clear PageCache, dentries & inodes.
# sync; echo 3 > /proc/sys/vm/drop_caches
The sync command above flushes system buffer. Writing to drop_caches file will clear cache without affecting any process or application. You can use ‘echo 1 >’ to clear PageCache, ‘echo 2 >’ to clear dentries & inodes, ‘echo 3 >’ to clear PageCache, dentries & inodes.
You can safely use ‘echo 1 >’ command in production systems.
You can automate this using a shell script. Create empty shell script file with the following command.
$ sudo vi /home/clear_cache.sh
Add the following lines to it. In this case, we will clear only PageCache
#!/bin/bash echo "echo 1 > /proc/sys/vm/drop_caches"
Save and close the file.
Make Shell Script executable with the following command.
$ sudo chmod 755 /home/clear_cache.sh
Next, we will create cronjob to run this script to run at 10.a.m daily. Open crontab file.
# crontab -e
Add the following lines to it.
0 10 * * * /home/clear_cache.sh
If you also want to clear swap space then run the following commands.
# swapoff -a && swapon -a
You may also add the above command to shell script created above.