Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 6 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

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .