Bash – How to keep a file under N lines long

bash

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?

Best Solution

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