Shell Script For Linux Clear Cache

Linux

Linux borrows unused RAM memory for disk caching due to this it looks like the system is low on memory. Usually you don’t need to do anything to clear this memory as Linux automatically manages the RAM and will allocate the cached memory when ever a application asks for the same.

However one of our customers had issue with free command output showing low on RAM and due to this there application health monitoring software was always on RED status and was sending notifications. So to avoid this scenario we created a shell script which checks for the free RAM percentage and clears the cache incase the free RAM hits the percentage mentioned in script.(default trigger: Free RAM =<15%ge of total memory)

Example from Redhat website:

Free Command Output

In this example the total amount of available memory is 4040360 KB. 264224 KB are used by processes and 3776136 KB are free for other applications. Do not get confused by the first line which shows that 28160KB are free! If you look at the usage figures you can see that most of the memory use is for buffers and cache. Linux always tries to use RAM to speed up disk operations by using available memory for buffers (file system metadata) and cache (pages with actual contents of files or block devices). This helps the system to run faster because disk information is already in memory which saves I/O operations. If space is needed by programs or applications like Oracle, then Linux will free up the buffers and cache to yield memory for the applications. If your system runs for a while you will usually see a small number under the field “free” on the first line.

Shell Script for Linux clear cache:

clear_RAM.sh:

 

#!/bin/bash

#Calculates the current percentage of free RAM available in system
_ram_avl=`free | grep Mem | awk '{print $4/$2 * 100.0}' | awk -F'.' '{print $1}'`

#If free percentage is less than equal to 15% of total RAM trigger the cleanup

if [ $_ram_avl -le 15 ]; then

echo "RAM available in system is below 15 percentage clearing cache and freeing up memory";
echo
free && sync && echo 3 > /proc/sys/vm/drop_caches && free
echo
sudo sysctl vm.drop_caches=1
echo
fi;

 

Setting up the Linux clear cache script:

• Login as root user to application server VM.
• Copy the clear_RAM.sh file to any folder. (We have considered as /opt/scripts)
• Provide execute privilege by using below command

chmod 0755 clear_RAM.sh

• Add the schedule to crontab following below commands

crontab -e
0 * * * * /opt/scripts/clear_RAM.sh
:wq

• Use contab -l command to check the cronjob is scheduled or not.

Sample Execution Output:

clear linux cache script output

References:

Redhat : Memory Usage and Page cache

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.