Every Linux System has three options to clear cache without interrupting any processes or services.
1. Clear PageCache only.
# sync; echo 1 > /proc/sys/vm/drop_caches
2. Clear dentries and inodes.
# sync; echo 2 > /proc/sys/vm/drop_caches
3. Clear PageCache, dentries and inodes.
# sync; echo 3 > /proc/sys/vm/drop_caches
If you want to clear Swap space, you may like to run the below command.
# swapoff -a && swapon -a
Also you may add above command to a cron 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.
# echo 3 > /proc/sys/vm/drop_caches && swapoff -a && swapon -a && printf 'n%sn' 'Ram-cache and Swap Cleared' OR $ su -c "echo 3 >'/proc/sys/vm/drop_caches' && swapoff -a && swapon -a && printf 'n%sn' 'Ram-cache and Swap Cleared'" root
After testing both above command, we will run command “free -h” before and after running the script and will check cache.
Image does not exist: https://www.tecmint.com/wp-content/uploads/2015/05/Clear-RAM-Cache.gif