I'm writing a script to calculate Memory Utilization Percentage in a Linux system. My script will be deployed in production which has many flavours of Linux CentOS.
So far, I have used free command, but there seems to be a problem with one OS version or the other.Problem is in some servers( eg. Linux CentOS 7.5.1804 (3.10.0-862.14.4.el7.x86_64)) , MEM% is more than 100, as the free command output differs in them. Keeping in mind the formula,
MEM%= 100-(((free+buffers+cached)*100)/TotalMemory).
I need a script to calculate memory percentage no matter what the flavour of OS it is.
I have tried calculating memory from top command | grep "Mem:" , but it is very arbitrary.
Thus I'm using the formula I have now.
It's ok that memory calculation can be complex and I just want reasonable percentage value which is close to real value .Any suggestion would be highly helpful.
total_perc=100
average=$( free -b | grep ":" | head -1 | tr -s ' ' | cut -d ':' -f2 | awk '{$1=$1};1' )
a1=$(echo $average | cut -d ' ' -f1) # Total
a2=$(echo $average | cut -d ' ' -f2) #Used
a3=$(echo $average | cut -d ' ' -f3) #Free
a4=$(echo $average | cut -d ' ' -f4) #Shared
a5=$(echo $average | cut -d ' ' -f5) #Buffers
a6=$(echo $average | cut -d ' ' -f6) #Cached
addition=$(( a3 + a5 + a6 ))
multi=$(( addition*100))
divis=$(awk -v dividend="${multi}" -v divisor="${a1}" 'BEGIN {printf "%.2f", dividend/divisor; exit(0)}')
percentage=$(awk -v no1="${total_perc}" -v no2="${divis}" 'BEGIN {printf "%.2f", no1-no2; exit(0)}')
echo "Final Memory Util Percentage : $percentage"
In some OS flavours, such as :Linux CentOS 7.5.1804 (3.10.0-862.14.4.el7.x86_64)", the utilization percentage crosses, 100.Kinldy guide me where I'm going wrong.
I need a OS flavour independent code for calculating Memory. Thanks in Advance.