# Calculate percent of memory used in Linux

WriteBash - How to calculate percent of memory used in Linux? This article will guide you to do that.

For Linux desktops, you can easily see the percentage of RAM used on your computer through programs like System Monitor. But for Linux servers, only the command line, you must use it.

### Free command in Linux

Linux provides a `free` command to allow you to see how much memory is used and how much is available.

To see the memory status, type the command below.

`\$ free -mth`
• Option `-m` : show output in megabytes.
• Option `-t` : show total for RAM + swap.
• And option `-h`: show human-readable output.

### Calculate percent of memory used

To calculate the percentage, it’s very simple, it’s just a mathematical formula.

Percentage = (memory used / total memory) * 100

First, we will get the total memory information available on the system with the following command. KB unit.

`\$ TOTAL_MEM=`free | grep Mem | awk '{print \$2}'``
• `grep Mem` : print out Memory line from `free` command result.
• `awk '{print \$2}'` : use `awk` command to print out column number 2.

Next, we get the memory information used by the command below. KB unit.

`\$ USED_MEM=`free | grep Mem | awk '{print \$3}'``
• `awk '{print \$3}'` : use `awk` command to print out column number 3.

And finally, we use the following command to calculate the percentage of memory used.

`\$ PERCENT=\$(awk "BEGIN {printf \"%.2f\",(\$USED_MEM/\$TOTAL_MEM)*100}")`
• `\$(awk "BEGIN {}")` : calculation expression using awk command in bash.
• `printf \"%.2f\"` : print out the results with 2 decimal places.
• `(\$USED_MEM/\$TOTAL_MEM)*100` : memory percentage expression.

Now the variable PERCENT already contains the percentage of memory used, you just need to use the command below to see the result.

`\$ echo \$PERCENT`

### Conclusion

I wrote this article because there is a fact that I have experienced. My boss wants me to monitor Linux systems but doesn’t want me to use third party agent software.

So I had to get the system information myself and calculate it. And I wrote a completely bash script monitor program. 