BASH:检查系统上安装的内存量作为健全性检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29271593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH: check for amount of memory installed on a system as sanity check
提问by ljwobker
As part of a bash install script, I'd like the script to do a sanity check that the target machine has at least a given amount of memory installed. Note that I'm NOT specifically worried about how much memory is currently used or allocated or available - for my purposes the existance of more than XXX GB of RAM in the system is sufficient. My current plan (which works, but seems possibly kludge-y?) is to do something along the lines of:
作为 bash 安装脚本的一部分,我希望脚本对目标机器至少安装了给定数量的内存进行完整性检查。请注意,我并不特别担心当前使用或分配或可用的内存量 - 就我而言,系统中存在超过 XXX GB 的 RAM 就足够了。我目前的计划(可行,但似乎可能是杂乱无章的?)是按照以下方式做一些事情:
MEM=`free -m | grep Mem | awk '{print }'`
And then just do a greater-than/less-than compare within the bash script on the $MEM variable. As I said, this works... but was just curious if there was a more elegant way to do this that others would suggest...
然后在 bash 脚本中对 $MEM 变量进行大于/小于比较。正如我所说,这有效......但只是好奇是否有其他人建议的更优雅的方式来做到这一点......
回答by paxdiablo
Actually, that's notkludgy, it the time-honoured way of doing things in UNIX-land, using simple tools in pipelines to build up more complex things.
实际上,这并不笨拙,它是 UNIX 领域由来已久的做事方式,在管道中使用简单的工具来构建更复杂的东西。
The onlything you need to watch out for is if the output format of free -m
ever changes. You may not think this would happen very often but, as someone who worked on a performance monitoring application using the output of various command-line tools, it happens more often than you'd think.
该只需要注意的是,如果输出格式free -m
都没有改变。您可能认为这种情况不会经常发生,但作为使用各种命令行工具的输出开发性能监控应用程序的人,这种情况发生的频率比您想象的要高。
If you want less of a pipeline, you could go directly to /proc/meminfo
to get what you want:
如果你想要更少的管道,你可以直接/proc/meminfo
去得到你想要的:
$ cat /proc/meminfo
MemTotal: 8291816 kB
MemFree: 3136804 kB
HighTotal: 0 kB
HighFree: 0 kB
LowTotal: 8291816 kB
LowFree: 3136804 kB
SwapTotal: 1310720 kB
SwapFree: 1077244 kB
So, if you're interested in total memory, you could use:
因此,如果您对总内存感兴趣,可以使用:
$ totalk=$(awk '/^MemTotal:/{print }' /proc/meminfo) ; echo $totalk
8291816
But, of course, the same caveats apply re the format of the "file", in that it may change in the future.
但是,当然,同样的警告也适用于“文件”的格式,因为它将来可能会发生变化。
Come to think of it, you could also simplify what you have,since there's no need for a separate grep
in the pipeline:
想想看,你也可以简化你所拥有的,因为grep
在管道中不需要单独的:
$ totalm=$(free -m | awk '/^Mem:/{print }') ; echo $totalm
8097