Calculate total memory using free -m

Hi

I am trying to calculate memory used by Linux System
free -m
total used free shared buffers cached
Mem: 32109 31010 1099 0 3600 7287
-/+ buffers/cache: 20121 11987
Swap: 10239 1282 8957

Now according to my requirement Im calculating memory using below cmd

free -m | awk 'NR==3{printf "Memory Usage: (%.2f%%)\n", $3*100/32109 }'

But in the above code 32109 is hard coded(Which is total memory highlighted in red color) now I want to make this as generic, how do I pass that value 32109 as a variable in code. How can this be achieved

Hello sam@sam,

Could you please let me know if this helps you.

free -m | awk 'NR==2{val=$2;next} NR==3{printf("Memory Usage: %.2f%\n", ($3*100)/val)}'

Thanks,
R. Singh

1 Like

Perfect its working
Thanks you RavinderSingh, for your help.