tags:

views:

128

answers:

4

I have a log that should have the latest N entries. There's no problem if the file is a bit bigger a few times.

My first attempt is periodically running:

tail -n 20 file.log > file.log

Unfortunately, that just empties the file. I could:

tail -n 20 file.log > .file.log; mv .file.log file.log

However, that seems messy. Is there a better way?

+6  A: 

It sounds like you are looking for logrotate.

alxp
Logrotate sounds great for general logs, but I need something more for special files not known beforehand. Also, my limit is for lines, not time. Thanks anyway, I will use it for other things.
eipipuz
+2  A: 

There are good answers for this here: http://stackoverflow.com/questions/123235/problem-with-bash-output-redirection

Bruno Rothgiesser
+1  A: 

logrotate, with size=xxx where xxx is the approximate size for 20 lines, and possibly delaycompress to keep the previous one also human readble.

Sunny
Thanks for noticing that I need more the line limit than the time period.
eipipuz
+2  A: 

I agree, logrotate is probably what you need. If you still want a command line solution, this will get the job done. Ex is a line editor. Nobody uses line editors anymore except for use in shell scripts. Syntax is for Sh/Ksh/Bash shells. I think it's the same in C shell.

ex log.001 << HERE
$
-20
1,-1d
w
q
HERE
Steve K
Vi's father! Yep that sounds really useful.
eipipuz