如何获取 Linux PC 的总物理内存(以字节为单位)?
我需要将其赋值给一个 bash 脚本变量。
grep MemTotal /proc/meminfo | awk '{print $2}'
返回的数字以KB为单位
awk '/MemTotal/{print $2}' /proc/meminfo
- ghostdog74grep MemTotal /proc/meminfo | awk '{print $2}' | xargs -I {} echo "scale=4; {}/1024^2" | bc
。请注意,该命令不会改变原始值,只是转换其显示格式。 - turtlemonvhawk '/MemFree/ { printf "%.3f \n", $2/1024/1024 }' /proc/meminfo
命令。原文链接在此(credit goes [here])。 - ostrokachawk '/MemFree/ { printf "%i\n", $2*1024 }' /proc/meminfo
- mpenphymem=$(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
while read -r a b c
以去除单位。 - dess在假设物理内存将是free命令输出的第一个数字的情况下,我提出了这个想法:
free -m | grep -oP '\d+' | head -n 1
这使您能够配置 free 输出您想要的单位 (-m, -g, ...),并且它独立于系统语言(其他答案依赖于 free 输出中的“Mem:”字符串,该字符串可能会根据语言而变化)。
var=$(free | awk '/^Mem:/{print $2}')
$()
语法。 - ghostdog74我会尽力让这个答案自解释,跟上我的节奏。
要获取内存描述,可以使用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 inMega Bytes
orGiga Bytes
just append-m
or-g
after-t
in abovefree
commands respectively.For Example :
free -t -g | grep -oP '\d+' | sed '10!d'
Output (in Giga Bytes on my PC) :
11
如果有人需要一个易于理解的版本:
var=$(free -h | awk '/^Mem:/{print $2}')
结果:
1.9G
freemem=$(echo -e 'import re\nmatched=re.search(r"^MemTotal:\s+(\d+)",open("/proc/meminfo").read())\nprint(int(matched.groups()[0])/(1024.**2))' | python)