views:

104

answers:

3

I am looking to create a cron job that opens a directory loops through all the logs i have created and deletes all lines but keep the last 500 for example.

I was thinking of something along the lines of

tail -n 500 filename > filename

Would this work?

I also not sure how to loop through a directory in bash

Thanks in advance.

A: 

In bash you loop over files in a directory, e.g. like this:

cd target/directory

for filename in *log; do
    echo "Cutting file $filename"
    tail -n 500 $filename > $filename.cut
    mv $filename.cut $filename
done
The MYYN
The `mv` should be conditional on the success of the `tail`.
Dennis Williamson
+1  A: 
DIR=/path/to/my/dir # log directory
TMP=/tmp/tmp.log # temporary file
for f in `find ${DIR} -type f -depth 1 -name \*.log` ; do
  tail -n 500 $f > /tmp/tmp.log
  mv /tmp/tmp.log $f
done
Paul R
`for foo in $(find)` is a bad habit to develop. Either use `find | while read` or globbing. And the `mv` should be conditional on the success of the `tail`.
Dennis Williamson
@Dennis: thanks - can you explain why `for foo in $(find ...)` is a bad habit ?
Paul R
If there are filenames with spaces, it will see those as multiple separate names.
Dennis Williamson
@Dennis: thanks - I hadn't realised that
Paul R
+3  A: 

Think about using logrotate.
It will not do want you want (delete all lines but the last 500), but it can take care of too big logfiles (normally by comressing the old ones and deleting them at some point). Should be widely available.

tanascius