purge logs, keep the 30 lasts

Hi,

I have to make a script to purge logs in a directory (this script will run automatically every day) and this script has to keep just the 30 last files.
So I want it to count all the files in the directory, find the 30 most recents and delete the others.

I just started shell scripting and I'm not very good ^^
I tried this :

#!/bin/sh
FIND=/opt/csw/bin/gfind
DIR=<path to the directory where logs are>
DIR2=<path where the script is>
CREATE_FILE=`ls -ltr $DIR|cut -c54- > $DIR2/lstFile`;
NB_LINE=`cat $DIR2/lstFile|wc -l`;
deb=`expr $NB_LINE - 30`
FileToDelete=`head -n $deb lstFic> lstFileDel`;
DEL_FILE=`cat lstFileDel`
echo $DEL_FILE
$FIND $DIR -type f -name '$DEL_FILE' -exec rm -f {} \;

but the find rm doesn't work, my variable is good the echo displays the files to delete, but the rm does't work...

so if anyone has an idea?or a better solution (I gues there must be a lot^^)

thanks for the help :slight_smile:

try this:

cd <path to the directory where logs are>
rm -f `ls -lt | awk ' NR>30 { print $NF } '`

works great :smiley:
I think I made it complicated for nothing

thanks a lot! :wink:

ls -lt |grep -v ^d | awk ' NR>30 { print $NF } ' |xargs rm 
# rm `ls -1t | sed '1,29d;s/.* \(.*\)$/\1/'`