Get separate used memory info from free -m command

18,751

Solution 1

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).

Solution 2

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.

Solution 3

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.

Solution 4

with bash free and grep only

read junk total used free shared buffers cached junk < <(free -m  | grep ^Mem)
echo $used
Share:
18,751

Related videos on Youtube

KK Patel
Author by

KK Patel

Cloud Infrastructure and DevOps Expert with around decade experience in IT Infrastructure. Expert in Designing and building Infrastructure as code, automation of cloud infrastructure provisioning , system provisioning , apps/Micro services deployments , CI/CD pipelines , building highly available and reliable IT Infrastructure platforms.

Updated on September 18, 2022

Comments

  • KK Patel
    KK Patel almost 2 years

    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%?

    • Brian D
      Brian D almost 4 years
      note that -m part is optional and simply converts the output number from kB to mB.
  • peterph
    peterph over 11 years
    @user34571 thanks for pointing out the double % issue. You may also want to put these things into comment next time (to get some credits :)).