如何在Bash中获取总物理内存并将其分配给一个变量?

54

如何获取 Linux PC 的总物理内存(以字节为单位)?

我需要将其赋值给一个 bash 脚本变量。


这个问题的意思不是很清楚,请尝试重新表述得更具体。 - Gabe
我刚刚重写了它。对我来说这非常具体,我必须获取我的电脑的总物理内存(RAM)并将其分配给我的bash脚本中的一个变量。 - Neuquino
7个回答

78
grep MemTotal /proc/meminfo | awk '{print $2}'  

返回的数字以KB为单位


13
看起来你已经回答了自己的问题。然而,使用一个awk命令来完成任务。awk '/MemTotal/{print $2}' /proc/meminfo - ghostdog74
9
如果你需要将结果转换为其他进制(例如GB),可以使用以下命令:grep MemTotal /proc/meminfo | awk '{print $2}' | xargs -I {} echo "scale=4; {}/1024^2" | bc。请注意,该命令不会改变原始值,只是转换其显示格式。 - turtlemonvh
4
@turtlemonvh 或者您可以执行 awk '/MemFree/ { printf "%.3f \n", $2/1024/1024 }' /proc/meminfo 命令。原文链接在此(credit goes [here])。 - ostrokach
字节: awk '/MemFree/ { printf "%i\n", $2*1024 }' /proc/meminfo - mpen

26
phymem=$(awk -F":" '$1~/MemTotal/{print $2}' /proc/meminfo )

或使用免费版

phymem=$(LANG=C free|awk '/^Mem:/{print $2}')

或者使用Shell

#!/bin/bash

while IFS=":" read -r a b
do
  case "$a" in
   MemTotal*) phymem="$b"
  esac
done <"/proc/meminfo"
echo $phymem

6
我喜欢这个程序,因为你可以通过传入“-m”,“-g”等参数来使用“free”命令以不同的单位获取结果 :) - Adrian Petrescu
非常好的总结回答,谢谢。此外,我会将适当的行更改为 while read -r a b c 以去除单位。 - dess

14

在假设物理内存将是free命令输出的第一个数字的情况下,我提出了这个想法:

free -m | grep -oP '\d+' | head -n 1

这使您能够配置 free 输出您想要的单位 (-m, -g, ...),并且它独立于系统语言(其他答案依赖于 free 输出中的“Mem:”字符串,该字符串可能会根据语言而变化)。


9
如何?
var=$(free | awk '/^Mem:/{print $2}')

1
不要在变量赋值时使用等号之间的空格。尽可能使用 $() 语法。 - ghostdog74

2

我会尽力让这个答案自解释,跟上我的节奏。

要获取内存描述,可以使用free实用程序:

free -t

输出(以KB为单位):

              total        used        free      shared  buff/cache   available
Mem:        8035900     3785568      324984      643936     3925348     3301908
Swap:       3906556      271872     3634684
Total:     11942456     4057440     3959668

为了从这个输出中提取所有这些到一个列中:
free -t | grep -oP '\d+'

输出(以KB为单位):

8035900
3866244
266928
650348
3902728
3214792
3906556
292608
3613948
11942456
4158852
3880876

注意:值之间可能存在微小差异,大多数情况下这并不重要。

如果你只想获取总物理内存(包括内存和交换空间),它是上面输出中的第10个值:

free -t | grep -oP '\d+' | sed '10!d'

输出结果(在我的电脑上)

11942456

Note: All the above outputs are in Kilo Bytes. If you want in Mega Bytes or Giga Bytes just append -m or -g after -t in above free commands respectively.

For Example :

free -t -g | grep -oP '\d+' | sed '10!d'

Output (in Giga Bytes on my PC) :

11

1

如果有人需要一个易于理解的版本:

var=$(free -h | awk '/^Mem:/{print $2}')

结果:

1.9G

1
傻瓜式的内联Python版本,看起来过于复杂,但实际上非常有用。
freemem=$(echo -e 'import re\nmatched=re.search(r"^MemTotal:\s+(\d+)",open("/proc/meminfo").read())\nprint(int(matched.groups()[0])/(1024.**2))' | python)

它返回内存的大小,单位为GB。

我认为你的're.search(r"^MemTotal...")'中有一个多余的'r'。 - kd88
@kd88 我认为没问题。这只是Python中原始字符串的表示法。请参阅正则表达式文档的介绍部分以获取解释:https://docs.python.org/2/library/re.html - turtlemonvh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接