Check available memory in Linux
You can also read the source of free
's information, /proc/meminfo
:
~ head /proc/meminfo
MemTotal: 4039168 kB
MemFree: 2567392 kB
MemAvailable: 3169436 kB
Buffers: 81756 kB
Cached: 712808 kB
SwapCached: 0 kB
Active: 835276 kB
Inactive: 457436 kB
Active(anon): 499080 kB
Inactive(anon): 17968 kB
In Python, for example:
with open('/proc/meminfo') as file:
for line in file:
if 'MemFree' in line:
free_mem_in_kb = line.split()[1]
break
will get you the free memory in KB in the free_mem_in_kb
variable. With something similar for total memory, you can subtract the values (or add up buffers, cached, etc.).
You could also create a dictionary of the values in the file:
from collections import namedtuple
MemInfoEntry = namedtuple('MemInfoEntry', ['value', 'unit'])
meminfo = {}
with open('/proc/meminfo') as file:
for line in file:
key, value, *unit = line.strip().split()
meminfo[key.rstrip(':')] = MemInfoEntry(value, unit)
Then retrieve the values with meminfo['MemAvailable'].value
, for example.
Percentage used memory (excluding buffers and cache):
free | awk 'FNR == 3 {print $3/($3+$4)*100}'
For your question you added: "above 7.2 gigabyte", but I would assume a percentage might be more flexible.
To expand on this, the same can be used for "percentage free memory":
free | awk 'FNR == 3 {print $4/($3+$4)*100}'
awk
is a pattern scanning tool with loads and loads of parameters. FNR is the input record number in the current input file. Basically the line that is currently processed. So FNR will scan for the 3rd line where the numbers are what you want. The $3 and $4 point to the 3rd and 4th column. If you want the number itself, use:
free | awk 'FNR == 3 {print $3}'
free | awk 'FNR == 3 {print $4}'
Example:
$ free
total used free shared buffers cached
Mem: 16419996 16144316 275680 0 447220 12589412
-/+ buffers/cache: 3107684 13312312
Swap: 16761852 38532 16723320
~$ free | awk 'FNR == 3 {print $3}'
3109056
~$ free | awk 'FNR == 3 {print $4}'
13311240
If you want with buffers and cache: FNR=2. If you want swap, FNR=4.