Posted: . At: 10:29 AM. This was 4 years ago. Post ID: 14143
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


How to print the RAM value as a number with Linux. This could be very useful in a script.


Printing the value of RAM as a number is tricky but doable.

This example will print the amount of RAM installed in your machine.

4.4 Mon Mar 09 jason@Yog-Sothoth 0: $ awk '/^MemTotal/{ print $2/1000 }' /proc/meminfo
12138.6

This is another example, I could not work out how to get the piped value as a variable, but this method is fine, using 0 decimal points.

4.4 Mon Mar 09 jason@Yog-Sothoth 0: $ export mem=`grep "MemTotal" /proc/meminfo | sed 's/[^0-9]*//g'` ;echo "scale = 0; $mem / 1000" | bc -l
12138

This was actually pretty tricky to work out, but nice at the same time. It is very good to finally work something out like this. The second example creates a variable that contains the output of the first commands, then it can be fed into bc. This is a great way to handle tricky piping.

This is yet another example of the same trick.

4.4 Mon Mar 09 jason@Yog-Sothoth 0: $ free | sed -n '2{p;q}' | awk '{print $2}'
12138648

The sed -n '2{p;q}' command prints only the second line of output, then the awk '{print $2}' command prints only the second column of text.

This is a very useful tip.

To print the amount of RAM in a whole number, you may do it like this.

┌──[jason@11000000.10101000.00000001.00000010][~]
└──╼  ╼ $ free -h | gawk '/Mem:/{print $2}' | awk 'FNR == 1 {print $1 "B"}'
15GiB

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.