0

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?

eipipuz
  • 563
  • 1
  • 7
  • 16
  • 1
    It's messy, but it works, right? – Alan Jun 17 '09 at 17:08
  • There are good answers for this here: [http://stackoverflow.com/questions/123235/problem-with-bash-output-redirection](http://stackoverflow.com/questions/123235/problem-with-bash-output-redirection) – b.roth Jun 17 '09 at 17:17

3 Answers3

6

It sounds like you are looking for logrotate.

alxp
  • 6,153
  • 1
  • 22
  • 19
  • 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 Jun 17 '09 at 17:28
2

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
  • 2,124
  • 16
  • 19
1

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 Milenov
  • 21,990
  • 6
  • 80
  • 106