Hello everyone, in this post I will provide information about how to clear cache on Linux. In the Linux operating system, there is way to clean it. Okay, here’s how:
3 Commands to Clear Cache on Linux
Here are 3 options available on linux :
1. Clear only pageCache
sync; echo 1 > /proc/sys/vm/drop_caches
In this option, the cache that is deleted is only pageCache. This is what I use most often on the webserver that I handle.
2. Clear dentries and inodes
sync; echo 2 > /proc/sys/vm/drop_caches
In this option, the cache that is deleted is dentries and inodes.
3. Clear cache (All)
sync; echo 3 > /proc/sys/vm/drop_caches
In this option, both pageCache, dentries and inodes will be deleted. Use this if you really understand what you want to do.
Command to clear SWAP Memory
If you also want to clear swap memory, run the following command :
swapoff -a && swapon -a
Schedule clear cache command on a cronjob
On the server, I usually schedule regular clear cache every night to refresh my server. If you want to do that too, please create a shellscript file to enter the clear cache command, for example :
vim /usr/local/sbin/clearCache.sh
You are free to name the file and place it as you wish, then enter the following code :
#use this for only clearCache sync; echo 1 > /proc/sys/vm/drop_caches && echo "cache cleared" #use this for clearCache and swap memory sync; echo 1 > /proc/sys/vm/drop_caches && ( swapoff -a && swapoff -a ) && echo "cache and swap memory cleared"
save, then open the cronjob editor :
crontab -e
register the shellscript file into the cronjob and run it every night (example: every 1am)
00 01 * * * sh /usr/local/sbin/clearCache.sh
Save that, then the cronjob will automatically clear the cache every night. For more details on cronjob scheduling, you can read my article Rules on CronJob.
Create bashscript to clear cache
if you think typing the clear cache command is too long, you can make a bash alias. Open your linux bash file :
vim ~/.bashrc
then, enter the following code :
#use this for only clearCache alias clearCache = 'sync; echo 1 > /proc/sys/vm/drop_caches && echo "cache cleared"' #use this for clearCache and swap memory alias clearCache = 'sync; echo 1 > /proc/sys/vm/drop_caches && ( swapoff -a && swapoff -a ) && echo "cache and swap memory cleared"'
after that save and reload your bash file with the command :
source ~/.bashrc
If done, by typing clearCache
command is the same as running the clear cache command.
for more details about bash aliases, you can read my article on Create and Use Bash Alias on Linux.
Well, those are how to clear cache on linux that I can share. Hopefully this information can be useful, Thank you 😀
0 Comments