0

I am trying to do following:

Get output of free -mo , take the 2nd line and log it to a file every 30 seconds.

When I run

$free -mo -s 30 

It runs and displays output every 30 seconds.

But when I run

$ free -mo -s 30 | head -2 | tail -1

It runs only once. I am not able to figure out what is wrong.

free Manual says free -s 30 run the command every 30 seconds.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Learn More
  • 1,535
  • 4
  • 29
  • 51
  • 2
    Use [`watch`](http://linux.die.net/man/1/watch). – DCoder Dec 31 '12 at 15:16
  • DCoder: This should really be an answer! – Mats Petersson Dec 31 '12 at 16:27
  • @MatsPetersson: after re-reading the question, the OP wants to log the results to a file, `watch` is for interactive viewing and redirecting its output to a file pollutes it with control codes... probably more work than just building a manual while/sleep loop. – DCoder Jan 01 '13 at 08:53

5 Answers5

6

head -2 returns only the first 2 lines of output then quits. tail -1 returns the last line, then quits. When any program quits in a pipeline, it kills the entire pipeline, so free is stopped when head and tail finish.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
0

Use free -mo -s 30 &> test.txt &

This will take all of the output from the free command and output it to test.txt and run it in the background.

Will C.
  • 599
  • 3
  • 8
0

Try

free -mos 30 | grep 'Mem:' >yourlog.txt

(but you might be better considering something like sar to capture this kind of data - it can also reports lots of other things - just postpone the filtering/extraction until you generate a resport from the data).

symcbean
  • 47,736
  • 6
  • 59
  • 94
0

Will Hartung is right. Instead do this:

while true; do free -mo | head -2 | tail -1; sleep 30; done

0

Thanks to your answers. I was trying to monitor memory utilization of a process. I think I got it.

START_TIME=$(date);
cd /data;

INPUT_DATA=$1;
CODE_FILE=$2;
TIMES=$3;

echo "$START_TIME" > "$CODE_FILE.freeMemory_$TIMES.log";
free -mo -s 30 >> "$CODE_FILE.freeMemory_$TIMES.log" &
freepid=$!;

sleep 1m;
#echo "PID generated for free command -- $freepid";
START_TIME=$(date);
i=0;
while [ $i -le $TIMES ]
    do
            sh runCode.sh $CODE_FILE "output.csv" $INPUT_DATA;
            i=`expr $i + 1`
    done

END_TIME=$(date);
echo "process started at $START_TIME and ended at $END_TIME " ;
sleep 1m;
kill -9 $freepid;
END_TIME=$(date);
echo "$END_TIME" >> "$CODE_FILE.freeMemory_$TIMES.log";
Learn More
  • 1,535
  • 4
  • 29
  • 51