inthuriel
4/24/2018 - 8:19 AM

System cache free bash script

Bash script to clean system caches in Linux OS

#!/bin/sh
 ###########################################################################
# use freemem [lvl] [limit to run /num//unit/] [limit to 0- total 1- cache] #
# example usage ./freemem 3 3G 0                                            #
# author Mikolaj 'Metatron' Niedbala                                        #
# licenced GNU/ GPL                                                         #
 ###########################################################################
echo $1 $2 $3
if [ "$1" -gt "3" ]; then 
	echo "Cache cleaning level out of range"
	exit 1
fi	
 
#get total memory
TOTALMEM=`cat /proc/meminfo | grep MemTotal | grep -o "[0-9]\{1,\}"`

#get free memory
MEMFREE=`cat /proc/meminfo | grep MemFree | grep -o "[0-9]\{1,\}"`

#calculate used memory
if [ "$3" -eq "0" ]; then
	USEDMEM=$(($TOTALMEM - $MEMFREE))
elif [ "$3" -eq "1" ]; then
	USEDMEM=`cat /proc/meminfo | grep ^Cached | grep -o "[0-9]\{1,\}"`
else
	echo "Define if calculate form whole memory or cached only"
	exit 1
fi

#calculate limit
UNITMEM=`echo $2 | tr '[:upper:]' '[:lower:]' | grep -o "[a-z]\{1,\}$" | awk 'BEGIN { FS = "" } ; { print $1 }'`
LIMITMEM=`echo $2| grep -o "[0-9]\{1,\}"`

if [ "$LIMITMEM" -le "0" ]; then 
	echo "Memory limit is out of range"
	exit 1
fi	

if [ `echo $UNITMEM | grep -v "[k|m|g]"` ]; then
	echo "Unit is out of scope, should be [k|m|g]"
	exit 1
fi;

case $UNITMEM in
  "g") LIMITMEM=$(($LIMITMEM * 1024 * 1024)) ;;
  "m") LIMITMEM=$(($LIMITMEM * 1024)) ;;
  "k") LIMITMEM=$(($LIMITMEM)) ;;
  *) LIMITMEM=$(($LIMITMEM)) ;;
esac

#cache clean or exit
if [ "$USEDMEM" -gt "$LIMITMEM" ]; then
	echo "Memory limit exceed, droping caches."
	sync; echo $1 > /proc/sys/vm/drop_caches	
	exit 0
else
	echo "Memory is within defined limits. Nothing to do, exiting."
	exit 0
fi;