使用单个bash shell命令获取gb中的可用内存

Har*_*qui 5 linux bash shell

以下命令以千字节为单位返回可用内存

cat /proc/meminfo | grep MemFree | awk '{ print $2 }'

有人可以建议使用单个命令来获取gb中的可用内存吗?

tin*_*ink 21

只需稍微修改一下你自己的魔法咒语:

awk '/MemFree/ { printf "%.3f \n", $2/1024/1024 }' /proc/meminfo
Run Code Online (Sandbox Code Playgroud)

PS:尊敬的OP,如果你发现自己的grep调用AWK和在一行中你最有可能做是错误的;} ...同样的,在一个单独的文件调用的猫; 这几乎没有必要.


Ami*_*esh 7

最简单的是以下内容:

free -h
Run Code Online (Sandbox Code Playgroud)

以下是输出截图:

在此处输入图片说明

更多细节 :

描述

   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)
Run Code Online (Sandbox Code Playgroud)


Ran*_*ein 5

freemem_in_gb () { 
    read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
    bc <<< "scale=3;${freemem}/1024/1024"
}
Run Code Online (Sandbox Code Playgroud)

请注意,scale=3可以更改为其他值,以获得更好的精度。因此,例如,我们可以编写一个采用精度参数的函数,如下所示:

freemem_in_gb () { 
    prec=$1;
    read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
    bc <<< "scale=${prec:-3};${freemem}/1024/1024"
}
Run Code Online (Sandbox Code Playgroud)

这将采用(或使用 3 作为默认值)并将精度参数传递给bc的scale选项

使用示例:

$ freemem_in_gb
5.524
$ freemem_in_gb 7
5.5115814
Run Code Online (Sandbox Code Playgroud)

编辑 感谢@Stephen P 和@Etan Reisner 留下评论并改进这个答案。代码进行了相应的编辑。

grep的长选项--fixed-strings是故意使用的,而不是-F为了fgrep解释原因。