I would like to get the available memory reported as a percentage using a Linux command line.
I used the free command, but that is only giving me numbers, and there is no option for percentage.
Join Stack Overflow to learn, share knowledge, and build your career.
Using the free command:
% free
total used free shared buffers cached
Mem: 2061712 490924 1570788 0 60984 220236
-/+ buffers/cache: 209704 1852008
Swap: 587768 0 587768
Based on this output we grab the line with Mem and using awk pick specific fields for our computations.
This will report the percentage of memory in use
% free | grep Mem | awk '{print $3/$2 * 100.0}'
23.8171
This will report the percentage of memory that's free
% free | grep Mem | awk '{print $4/$2 * 100.0}'
76.5013
You could create an alias for this command or put this into a tiny shell script. The specific output could be tailored to your needs using formatting commands for the print statement along these lines:
free | grep Mem | awk '{ printf("free: %.4f %\n", $4/$2 * 100.0) }'
free -t | grep "buffers/cache" | awk '{print $4/($3+$4) * 100}' also works quite well as it reports numbers that match Mem in htop/top
– Kevin Jalbert
May 14 '12 at 15:20
grep & go straight to awk: free | awk '/buffers\/cache/{print $4/($3+$4) * 100.0;}'
– Wrikken
May 23 '13 at 13:47
free | awk '/Mem/{printf("used: %.2f%"), $3/$2*100} /buffers\/cache/{printf(", buffers: %.2f%"), $4/($3+$4)*100} /Swap/{printf(", swap: %.2f%"), $3/$2*100}'
– Ben Lessani - Sonassi
Apr 4 '14 at 19:06
free -m, I don't have the third line "-/+ buffers/cache:"
– John Smith Optional
Oct 31 '15 at 23:56
free | awk '/Mem/{printf("Mem used: %.1f%"), $3/($2+.000000001)*100} /buffers\/cache/{printf(", buffers: %.1f%"), $4/($3+$4)+.000000001*100} /Swap/{printf(", swap: %.1f%"), $3/($2+.000000001)*100}'; without division by zero
– ǝlpoodooɟƃuooʞ
May 6 '19 at 13:46