Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to write a command that pipes the continuous output of a free command (run every second) to an awk command that parses a specific value (available free memory) and outputs this to a file with a timestamp. Here are my current attempts at the command:

free -mto -s 1 | awk '/Mem/ { print strftime("%r") "," $4 }' >>memOut

And alternatively, after a bit of Googling

free -mto -s 1 | awk '/Mem/ { print strftime("%r") "," $4 >>"memOut"}'

Each run produces empty files. Any suggestions or possibly different methods?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

You have to flush the buffer to see something in memOut during the execution:

free -mto -s 1 | awk '/Mem/ { print strftime("%r") "," $4; fflush(stdout) }' >> memOut

Here's an alternative version:

while sleep 1; do sed -n "s/MemFree: */`date`, /p" /proc/meminfo; done >> memOut
share|improve this answer
    
This gave me the output file I wanted. Thank you! –  Mark Jan 16 '12 at 19:54
add comment

Just to make sure that you are getting what you actually want and not what you specifically asked.

If you want to know available memory on the system for programs then this might be more suitable:

free -m -s 1 | awk '/buffers\/cache/ { print strftime("%r") "," $4; fflush(stdout) }' >> memOut

Mem line's Used column includes caches and buffers and in most cases when you want to monitor memory usage for given computer/task those should at least be noted.

share|improve this answer
    
Thanks for the tip! –  Mark Jan 16 '12 at 23:28
add comment

For old versions of awk you may have to use system("").

Actually, fflush(stdout) is for only for recent versions of awk and gawk, as its only in the POSIX standard since December 2012.

free -mto -s 1 | awk '/Mem/ { 
    print strftime("%r") "," $4;
    system(""); # Flush output
}' >> memOut

Note that using system("") flushes every file descriptor, its full description is in the gawk manual, section "9.1.4 Input/Output Functions".

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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