Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesnt "tail" work to truncate log files?

Tags:

ubuntu

I'm trying to manage my log file size using a cron script. I basically want to delete all but the last 2000 lines of the log file every night. I'm trying to run this command, but it seems to be emptying the entire file instead of doing what I want:

tail -2000 logfile.txt > logfile.txt

Does anyone know why this isn't working and/or how to accomplish what I want? Thanks!

like image 643
user77413 Avatar asked Nov 18 '09 22:11

user77413


2 Answers

You are overwriting the file before tail even starts to read it. The shell processes the > redirect operator, by clearing out the file first. Then it runs tail which has no data to read.

You can solve this by using a temporary file:

tail -2000 logfile.txt >logfile.tmp
mv logfile.tmp logfile.txt
like image 54
Greg Hewgill Avatar answered Nov 15 '22 14:11

Greg Hewgill


Here is another solution, without dealing with tmp files:

echo "`tail -2000 logfile.txt`" > logfile.txt
like image 35
udondan Avatar answered Nov 15 '22 15:11

udondan