Centos – How to get memory used(RAM used) using Linux command

centoscpanelmemory

I am trying to retrieve memory used(RAM) in percentage using Linux commands. My cpanel shows Memory Used which I need to display on a particular webpage.

From forums, I found out that correct memory can be found from the following:

free -m

Result:

-/+ buffers/cache:        492       1555

-/+ buffers/cache: contains the correct memory usage. I don't know how to parse this info or if there is any different command to get the memory used in percentage.

Best Answer

Here is sample output from free:

% free
             total       used       free     shared    buffers     cached
Mem:      24683904   20746840    3937064     254920    1072508   13894892
-/+ buffers/cache:    5779440   18904464
Swap:      4194236        136    4194100

The first line of numbers (Mem:) lists

  • total memory
  • used memory
  • free memory
  • usage of shared
  • usage of buffers
  • usage filesystem caches (cached)

In this line used includes the buffers and cache and this impacts free. This is not your "true" free memory because the system will dump cache if needed to satisfy allocation requests.

The next line (-/+ buffers/cache:) gives us the actual used and free memory as if there were no buffers or cache.

The final line (Swap) gives the usage of swap memory. There is no buffer or cache for swap as it would not make sense to put these things on a physical disk.

To output used memory (minus buffers and cache) you can use a command like:

% free | awk 'FNR == 3 {print $3/($3+$4)*100}'
23.8521

This grabs the third line and divides used/total * 100.

And for free memory:

% free | awk 'FNR == 3 {print $4/($3+$4)*100}' 
76.0657