1

I want to display free memory as a percentage. I'm pretty sure that I'm not displaying the free memory but the used one. Or am I wrong?

mem=`free -m | awk 'NR ==2{printf $3,$2,$3*100/$2}'`
echo $mem
1

Try this,

free | awk '/^Mem/ { a=(($3-$7)/$2 * 100); print a"% of Memory used"  }'
3.43143% of Memory used

free | awk '/^Mem/ { a=(($4+$7)/$2 * 100); print a"% of Memory free"  }'
96.5662% of Memory free

free | awk '/^Mem/ { a=(($7)/$2 * 100); print a"% of Memory cached"  }'
80.4204% of Memory cached

Note: crosscheck the values with glances

| improve this answer | |
2

If you want to display the amount of free memory as a percentage, Divide Column 4 (free) by Column 2 (total) and multiply the result by 100.

For example:

[user@localhost ~]$ free | awk '/^Mem/ { printf("free: %.2f %\n", $4/$2 * 100.0) }'
free: 97.32 %

If you want to show the amount used, you can divide column 3 (used) by column 2 (total) and multiply the result by 100.

[user@localhost ~]$ free | awk '/^Mem/ { printf("Used: %.2f %\n", $3/$2 * 100.0) }'
Used: 2.75 %

You can use %g for rounding to a specified number of significant digits.

For example, if you only want a whole number, and not a floating point value, you can change the number of floating point digits specified to 0 (zero). In this first example %.2f means 2 floating point values.

And here is an example with zero floating point values:

[user@localhost ~]$ free | awk '/^Mem/ { printf("Used: %.0f %\n", $3/$2 * 100.0) }'
Used: 3 %

This is also answered here:

https://stackoverflow.com/questions/10585978/linux-command-for-percentage-of-memory-that-is-free

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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