How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

278.1k views Asked by At

I'm typing a shell script to find out the total physical memory in some RHEL linux boxes.

First of all I want to stress that I'm interested in the total physical memory recognized by kernel, not just the available memory. Therefore, please, avoid answers suggesting to read /proc/meminfo or to use the free, top or sar commands -- In all these cases, their "total memory" values mean "available memory" ones.

The first thought was to read the boot kernel messages:

Memory: 61861540k/63438844k available (2577k kernel code, 1042516k reserved, 1305k data, 212k init)

But in some linux boxes, due to the use of EMC2's PowerPath software and its flooding boot messages in the kernel startup, that useful boot kernel message is not available, not even in the /var/log/dmesg file.

The second option was the dmidecode command (I'm warned against the possible mismatch of kernel recognized RAM and real RAM due to the limitations of some older kernels and architectures). The option --memory simplifies the script but I realized that older releases of that command has no --memory option.

My last chance was the getconf command. It reports the memory page size, but not the total number of physical pages -- the _PHYS_PAGES system variable seems to be the available physical pages, not the total physical pages.

# getconf -a | grep PAGES
PAGESIZE                           4096
_AVPHYS_PAGES                      1049978
_PHYS_PAGES                        15466409

My question: Is there another way to get the total amount of physical memory, suitable to be parsed by a shell script?

16

There are 16 answers

3
jaqque On BEST ANSWER

Using lsmem:

lsmem -b --summary=only | sed -ne '/online/s/.* //p'

returns the physical online memory in bytes. Without the -b will return a human-readable value.

lsmem is provided in the util-linux RPM (verified on CentOS 7, UBI 7, UBI 8, and UBI 9) which is either a direct, or indirect, dependency of systemd. You should be able to find the lsmem utility on any functional systemd based RHEL system.

3
AudioBubble On

If you're interested in the physical RAM, use the command dmidecode. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.

5
Rob On

Have you tried cat /proc/meminfo? You can then awk or grep out what you want, MemTotal e.g.

awk '/MemTotal/ {print $2}' /proc/meminfo

or

cat /proc/meminfo | grep MemTotal
2
André On

Total online memory

Calculate the total online memory using the sys-fs.

totalmem=0;
for mem in /sys/devices/system/memory/memory*; do
  [[ "$(cat ${mem}/online)" == "1" ]] \
    && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes)))));
done

#one-line code
totalmem=0; for mem in /sys/devices/system/memory/memory*; do [[ "$(cat ${mem}/online)" == "1" ]] && totalmem=$((totalmem+$((0x$(cat /sys/devices/system/memory/block_size_bytes))))); done

echo ${totalmem} bytes
echo $((totalmem/1024**3)) GB

Example output for 4 GB system:

4294967296 bytes
4 GB

Explanation

/sys/devices/system/memory/block_size_bytes

Number of bytes in a memory block (hex value). Using 0x in front of the value makes sure it's properly handled during the calculation.

/sys/devices/system/memory/memory*

Iterating over all available memory blocks to verify they are online and add the calculated block size to totalmem if they are.

[[ "$(cat ${mem}/online)" == "1" ]] &&

You can change or remove this if you prefer another memory state.

1
Howard_Roark On

I know this question was asked a long time ago, but I wanted to provide another way to do this that I found useful for an issue I just worked on:

lshw -c memory

lshw

lshw is a small tool to extract detailed information on the hardware configuration of the machine. It can report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache configuration, bus speed, etc. on DMI-capable x86 or IA-64 systems and on some PowerPC machines (PowerMac G4 is known to work).

3
JayEek On
free -h | awk '/Mem\:/ { print $2 }' 

This will provide you with the total memory in your system in human readable format and automatically scale to the appropriate unit ( e.g. bytes, KB, MB, or GB).

7
Cyril On

cat /proc/meminfo | grep MemTotal or free gives you the exact amount of RAM your server has. This is not "available memory".

I guess your issue comes up when you have a VM and you would like to calculate the full amount of memory hosted by the hypervisor but you will have to log into the hypervisor in that case.

cat /proc/meminfo | grep MemTotal

is equivalent to

 getconf -a | grep PAGES | awk 'BEGIN {total = 1} {if (NR == 1 || NR == 3) total *=$NF} END {print total / 1024" kB"}'
0
socketpair On
from pathlib import Path


def get_phys_mem_size() -> int:
    online_blocks = sum(i.joinpath('online').read_text().rstrip() == '1' for i in Path('/sys/devices/system/memory/').glob('memory*'))
    block_size = int(Path('/sys/devices/system/memory/block_size_bytes').read_text(), 16)
    return online_blocks * block_size
0
Raghu Ni On
dmidecode -t 17 | grep  Size:

Adding all above values displayed after "Size: " will give exact total physical size of all RAM sticks in server.

6
Sandip On

Add the last 2 entries of /proc/meminfo, they give you the exact memory present on the host.

Example:

DirectMap4k:       10240 kB
DirectMap2M:     4184064 kB

10240 + 4184064 = 4194304 kB = 4096 MB.

1
Yogesh Jilhawar On

One more useful command:
vmstat -s | grep memory
sample output on my machine is:

  2050060 K total memory
  1092992 K used memory
   743072 K active memory
   177084 K inactive memory
   957068 K free memory
   385388 K buffer memory

another useful command to get memory information is:
free
sample output is:

             total       used       free     shared    buffers     cached
Mem:       2050060    1093324     956736        108     385392     386812
-/+ buffers/cache:     321120    1728940
Swap:      2095100       2732    2092368

One observation here is that, the command free gives information about swap space also.
The following link may be useful for you:
http://www.linuxnix.com/find-ram-details-in-linuxunix/

1
Sandeep_black On

These are the ways :

1. /proc/meminfo

MemTotal: 8152200 kB

MemFree: 760808 kB

You can write a code or script to parse it.

2. Use sysconf by using below macros

sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);

3. By using sysinfo system call

int sysinfo(struct sysinfo *info);

struct sysinfo { .

   .

   unsigned long totalram;  /*Total memory size to use */

   unsigned long freeram;   /* Available memory size*/

   .

   . 

  }; 
0
Sathyam On

I find htop a useful tool.

sudo apt-get install htop

and then

free -m

will give the information you need.

0
Eduardo Cuomo On

Total memory in Mb:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
echo $((x/1024))

or:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo) ; echo $((x/1024))
1
bin456789 On

just use:

lsmem | grep "Total online memory:"

output is:

Total online memory:       4G

or with -b show output in bytes

Total online memory:         4294967296
0
firo On

In Linux Kernel, present pages are physical pages of RAM which kernel can see. Literally, present pages is total size of RAM in 4KB unit.

grep present /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'

The 'MemTotal' form /proc/meminfo is the total size of memory managed by buddy system.And we can also compute it like this:

grep managed /proc/zoneinfo | awk '{sum+=$2}END{print sum*4,"KB"}'