Bash free command stops working

776 Views Asked by At

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.

5

There are 5 best solutions below

0
On BEST ANSWER

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.

0
On

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";
0
On

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.

0
On

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).

0
On

Will Hartung is right. Instead do this:

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