How to get memory used(RAM used) using Linux command?
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
memoryused
memoryfree
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
I am going to mention on how to parse the information on free
command. To find the percentage, you can use as suggested in the other 2 answers.
This is clearly explained here. I would try to explain from what I have in my system.
free -m
total used free shared buffers cached
Mem: 7869 4402 3466 0 208 3497
-/+ buffers/cache: 696 7173
Swap: 3999 216 3783
Now, let us see what the various numbers actually represent.
Line1
- 7869 Indicates memory/physical RAM available for my machine.
- 4402 Indicates memory/RAM used by my system.
- 3466 Indicates Total RAM free and available for new process to run.
- 0 Indicates shared memory. This column is obsolete and may be removed in future releases of free.
- 208 Indicates total RAM buffered by different applications in Linux.
- 3497 Indicates total RAM used for Caching of data for future purpose.
Line2
-/+ buffers/cache: 696 7173
How to calculate the values 696 and 7173 obtained in Line2?
Total used (4402) - Total buffer RAM (208) - Total RAM for caching(3497) should constitute the Actual used RAM in the system. It returns me 697 which is the actual used RAM output in the second line.
Now, Total Available (7869) - Actual Used (696) should give you the free memory which is 7173 in this case which is also got as output in the second line.
Though a duplicate as pointed by @szboardstretcher , my preference from the solutions (in the original question) is the one below, specially since you want to parse to a webpage.
$ 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}'
Output:
used: 82.68%, buffers: 42.81%, swap: 1.27%