iamgroot
iamgroot

Reputation: 85

value of total physical memory in linux OS

I have a following question from this question. Is the value of the total physical memory always shown in KB? Because I would like to print it in GB and I use this command

grep MemTotal /proc/meminfo | awk '{$2=$2/(1024^2); print $2}'

I'm not sure wheter I should add a if statement to prove the command grep MemTotal /proc/meminfo showing KB value or other value

Any help would be appreciated

Upvotes: 1

Views: 198

Answers (3)

Léa Gris
Léa Gris

Reputation: 19545

If you assume the MemTotal: entry is always the first line of /proc/meminfo, it is possible to get the Gigabyte value without spawning a sub-shell or external commands, and using only POSIX-shell grammar that works with ksh, ash, dsh, zsh, or bash:

#!/usr/bin/env sh

IFS=': ' read -r _ memTotal _ < /proc/meminfo;

printf 'Total RAM: %d GB\n' "$((memTotal / 1024000))"

Upvotes: 1

Cyrus
Cyrus

Reputation: 88563

Is the value of the total physical memory always shown in KB?

Yes, the unit kB is fixed in the kernel code. See: 1 and 2

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133428

You need not to use grep + awk, you could do this in a single awk itself. From explanation point of view, I have combined your attempted grep code within awk code itself. In awk program I am checking condition if 1st field is MemTotal: and 3rd field is kB then printing 2rd field's value in GB(taken from OP's attempted code itself).

awk '$1=="MemTotal:" && $3=="kB"{print $2/(1024^2)}' /proc/meminfo

OR if in case you want to make kB match in 3rd a case in-sensitive one then try following code:

awk '$1=="MemTotal:" && $3~/^[kK][bB]$/{print $2/(1024^2)}' /proc/meminfo

Upvotes: 4

Related Questions