memory information on OS/X

Having used Linux for so long, you get pampered by the ‘everything including the kitchen sink’ listing of tools you can use. Well, one I took for granted for so many years is the command “free”… a simple command to show memory, buffer, and swap usage. Go figure, OS/X just had to take the typical UNIX approach and not include a simple ‘free’ command. (A lot like Solaris…ugh)
Sure, you can run ‘top’ to get the memory usage but that’s alot of info for just skimming the upper part of the screen for a little info. Looking around on the net for a brief stint I ran across a Python script that someone whipped up that would output the memory utilization. I used it, but it was using vm_stat instead of the full system memory output, and that upset me. I cried, and had to be held. But, I was able to pull up from such an ordeal and after I cleaned my keyboard, I wrote a small shell script that would do things right. I figured I’d post it here, so others wouldn’t have to reinvent the wheel. Here it is:
(NOTE: The first time I posted this, there was an error when the memory was returned in Gb instead of Mb in certain situations.  This has been fixed, and the new script posted below)

# Written for OS/X 10.6 to emulate Linux’s ‘free’ command
# just cuz I’m lazy and I likes it that way.
# Create initial output to parse data from.
TOP=`top -l 1 -n 0`

# grab ‘active’ memory usage
ACTIVE=`echo ${TOP} | awk ‘{ print $48 }’`
if [[ “${ACTIVE}” =~ “G” ]]; then
echo “inside if statement”
ACTIVE=$(echo ${ACTIVE} | sed ‘s/G//g’)
if [[ “${ACTIVE}” =~ “M” ]]; then
echo “inside M if statement”
ACTIVE=$(echo ${ACTIVE} | sed ‘s/M//g’)

# grab ‘free’ memory amount
FREE=`echo ${TOP} | awk ‘{ print $50 }’ | sed ‘s/M//g’`
# grab ‘swap’ memory being used. (in 4k pages)
SWAP=`echo ${TOP} | awk ‘{ print $60 }’ | awk -F \( ‘{ print $1 }’`
# calculate the total amount of memory by adding free and active.
echo “before calculating TOTAL:”
echo “ACTIVE is: ${ACTIVE}”
echo “FREE is: ${FREE}”

echo ”        total        used        free”
echo “Mem:        ${TOTAL}M        ${ACTIVE}M        ${FREE}M”
echo “-/+ buffers/cache:”
echo “Swap:                $((${SWAP}*4))”


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.