Skip to content
Advertisement

BASH: check for amount of memory installed on a system as sanity check

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:

MEM=`free -m  | grep Mem | awk '{print $2}'`

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…

Advertisement

Answer

Actually, that’s not kludgy, it the time-honoured way of doing things in UNIX-land, using simple tools in pipelines to build up more complex things.

The only thing 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.

If you want less of a pipeline, you could go directly to /proc/meminfo to get what you want:

$ 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 $2}' /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:

$ totalm=$(free -m | awk '/^Mem:/{print $2}') ; echo $totalm
8097
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement