8

As the output of the free -m command, I get the following:

             total       used       free     shared    buffers     cached
Mem:          2496       2260        236          0          5        438
-/+ buffers/cache:       1816        680
Swap:         1949         68       1881

I want to get only used memory, like 2260, as output. I tried the following command:

free -m | grep Mem | cut -f1 -d " " 

Help me to improve my command.

How can I get it as a percentage, like 35%?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
KK Patel
  • 1,845
  • 5
  • 22
  • 26
  • note that `-m` part is optional and simply converts the output number from kB to mB. – Brian D Aug 25 '20 at 21:39
  • Concerning the % part: this is how I display my laptop battery in [0.0 - 1.0]: `$(calc -d "$BR / 96000")`. – Vorac Jan 09 '23 at 15:23

5 Answers5

9

You can use awk without the need for a separate grep pipe for this:

awk '/^Mem/ {print $3}' <(free -m)

Where records/rows are filtered for those beginning with Mem and the third field/column ($3) is printed for the filtered record.

jasonwryan
  • 71,734
  • 34
  • 193
  • 226
6

Or with sed:

free -m | sed -n 's/^Mem:\s\+[0-9]\+\s\+\([0-9]\+\)\s.\+/\1/p'

Another solution would be:

free -m  | grep ^Mem | tr -s ' ' | cut -d ' ' -f 3

Credits for the second solution got to this post.

0x80
  • 853
  • 6
  • 7
5

As for the added question of displaying as percentage (based on jasonwryan's answer):

awk '/^Mem/ {printf("%u%%", 100*$3/$2);}' <(free -m)

get percentage by diving 3rd field by 2nd and print as an integer (no rounding up!).

EDIT: added double '%' in printf (the first one escapes the literal character intended for printing).

peterph
  • 30,520
  • 2
  • 69
  • 75
  • @user34571 thanks for pointing out the double `%` issue. You may also want to put these things into comment next time (to get some credits :)). – peterph Mar 20 '13 at 10:09
4

with bash free and grep only

read junk total used free shared buffers cached junk < <(free -m  | grep ^Mem)
echo $used
Jasen
  • 3,715
  • 13
  • 14
0

FNR =2 is 2nd row of output and {print $3} printing the 3rd column which is used

free -m | awk 'FNR == 2 {print $3}'
Laxmikant
  • 101