以下命令返回以千字节为单位的可用内存
cat /proc/meminfo | grep MemFree | awk '{ print $2 }'
有人建议使用单一命令来获取gb中的可用内存吗?
答案 0 :(得分:16)
对你自己的神奇咒语进行略微修改:
awk '/MemFree/ { printf "%.3f \n", $2/1024/1024 }' /proc/meminfo
P.S。:亲爱的OP,如果你发现自己在调用grep& awk在一行中你最有可能做错了;} ...与在一个文件上调用cat相同;这几乎没有理由。
答案 1 :(得分:4)
freemem_in_gb () {
read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
bc <<< "scale=3;${freemem}/1024/1024"
}
请注意,scale=3
可以更改为其他值,以获得更好的精确度。
因此,例如,可以编写一个将采用精度参数的函数,如下所示:
freemem_in_gb () {
prec=$1;
read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
bc <<< "scale=${prec:-3};${freemem}/1024/1024"
}
将采用(或使用3作为默认值)并将精度参数传递给bc
的{{1}}选项
使用示例:
scale
修改强> 感谢@Stephen P和@Etan Reisner留下评论并改进了这个答案。 代码已相应编辑。
出于解释原因,有意使用了{p>$ freemem_in_gb
5.524
$ freemem_in_gb 7
5.5115814
长选项grep
,而不是--fixed-strings
或-F
。
答案 2 :(得分:1)
最简单的方法如下:
free -h
下面是输出截图:
更多详细信息:
说明
free - displays the total amount of free and used physical and swap mem‐
ory in the system, as well as the buffers and caches used by the ker‐
nel. The information is gathered by parsing /proc/meminfo. The dis‐
played columns are:
total Total installed memory (MemTotal and SwapTotal in /proc/meminfo)
used Used memory (calculated as total - free - buffers - cache)
free Unused memory (MemFree and SwapFree in /proc/meminfo)
shared Memory used (mostly) by tmpfs (Shmem in /proc/meminfo, available
on kernels 2.6.32, displayed as zero if not available)
buffers
Memory used by kernel buffers (Buffers in /proc/meminfo)
cache Memory used by the page cache and slabs (Cached and Slab in
/proc/meminfo)
buff/cache
Sum of buffers and cache
available
Estimation of how much memory is available for starting new
applications, without swapping. Unlike the data provided by the
cache or free fields, this field takes into account page cache
and also that not all reclaimable memory slabs will be reclaimed
due to items being in use (MemAvailable in /proc/meminfo, avail‐
able on kernels 3.14, emulated on kernels 2.6.27+, otherwise the
same as free)
答案 3 :(得分:0)
如果你有python,你可以这样做:
python -c "import os;print int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3))"
在此示例中,我使用round
舍入到最接近的GB。你可以把它变成像这样的shell函数:
get_mem(){
MEM=$(python -c "import os;print int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3))")
echo $MEM
}
答案 4 :(得分:0)
如果你有python,你可以这样做:
获取总可用内存:
python -c "import os;print(int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3)))"
在此示例中,我使用 round
舍入到最近的 GB。你可以像这样把它变成一个 shell 函数:
get_mem(){
MEM=$(python -c "import os;print(int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3)))")
echo $MEM
}
要获得可用内存和已用内存,请查看 psutil
here。