Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I'm using awesome wm with bashets to make a little text widget to display the free memory. I wanted to convert the number from total kB to gigs (i.e. 1.2). this is what I came up with...

mem_Kb=$(grep -i memfree /proc/meminfo | cut -d: -f2 | tr -d [kB] | sed "s/^[ \t]*// ; s/[ \t]*$//")

mem_Gig=$(echo "scale = 1 ; $mem_Kb / 1000000" | bc )

echo mem_Gig: $mem_Gig

what are some better / cleaner ways?

share|improve this question

marked as duplicate by slm, Anthon, jasonwryan, vonbrand, Gilles Jun 9 '13 at 23:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

2 Answers 2

Just use free:

$ free -h
             total       used       free     shared    buffers     cached
Mem:          7.8G       6.8G       1.0G         0B       166M       4.2G
-/+ buffers/cache:       2.5G       5.2G
Swap:         7.8G       548K       7.8G

So, in your case:

$ mem_Gig=`free -h | awk '$2~/buf/{print $4}'`
$ echo $mem_Gig

From man free:

   -h, --human
          Show all output fields automatically scaled to
          shortest  three  digit  unit  and  display the
          units of print out.  Following units are used.

            B = bytes
            K = kilos
            M = megas
            G = gigas
            T = teras

          If unit is missing, and you have  petabyte  of
          RAM  or  swap,  the number is in terabytes and
          columns might not be aligned with header.

   --si   Use power of 1000 not 1024.

So, if you want to use 1000, not 1024, you can do:

$ mem_Gig=`free -h --si | awk '$2~/buf/{print $4}'`
$ echo $mem_Gig
share|improve this answer
@don_crissti OK, answer updated to give both options. –  terdon Jun 9 '13 at 15:48
much cleaner. thank you –  skinney6 Jun 10 '13 at 14:22
add comment
mem_Gig=$(gawk '( $1 == "MemFree:" ) { print $2*1024/1000000000 }' /proc/meminfo)
echo mem_Gig: $mem_Gig
share|improve this answer
I've got a lot to learn. thanks for you help –  skinney6 Jun 10 '13 at 14:23
@user1855481 - you could also use gawk (awk) with printf if you want to display only a certain number of decimals, e.g. mem_Gig=$(gawk '( $1 == "MemFree:" ) { printf ("%.2f\n", $2*1024/1000000000) }' /proc/meminfo); echo mem_Gig: $mem_Gig would display only two decimals (if you replace "%.2f\n" with "%.1f\n" it displays just one and so on). –  don_crissti Jun 10 '13 at 14:36
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.