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!
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
Here is another solution, without dealing with tmp files:
echo "`tail -2000 logfile.txt`" > logfile.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With