Tuesday 30 June 2009

Tip of the Day: Make a Memory Usage Script

Here's a simple memory usage script made in Bash, which will use the parsed output of free -tom utility. First, here is what the -tom argument stands for:

-t displays a line containing the total amount of memory (physical memory + swap)
-o disables the display of a buffer line
-m displays sizes in MB

Here goes the script, which outputs the total, used and free memory:

#!/bin/bash

# total memory
memt=$(free -tom | grep "Total:" | awk '{print $2}')
# used memory
memu=$(free -tom | grep "Total:" | awk '{print $3}')
# free memory
memf=$(free -tom | grep "Total:" | awk '{print $4}')
echo "Total memory: $memt MB"
echo "Used memory: $memu MB"
echo "Free memory: $memf MB"

You can put this in a file of your choice, say memory.sh, make it executable (chmod 755 memory.sh), put it inside ~/bin (or a directory of your choice) and then include that directory in your $PATH, so you'll be able to run the script just by typing memory.sh.

2 comments:

jdbauman said...

It's a sad day when awk gets used like this... If you're going to use awk, you might as well use it to its full potential. You could have just used cut for what you did here. How about reducing the entire script to a single line, like this:

free -tom | awk '/Total:/ {print "Total memory: "$2" MB\nUsed memory: "$3" MB\nFree memory: "$4" MB"}'

I enjoy your blog, but the scripting could use some work...

Also, I'm mostly interested in how much real memory I have available, not memory plus swap. If the system is swapping, it's a problem, and your script here is not going to give you the first clue on that. Not sure what's wrong with just using free -tom?

Anonymous said...

Here is the script I use:
http://ardchoille42.blogspot.com/2009/08/bash-script-convenient-display-of.html

This is a convenient way of interpreting the used, free and total amounts of memory and swap.