I am trying to create a Korn Shell script to be run every 5-10 minute from a crontab. This script needs to look for log files (transaction_<date>.log). If there are more than 5 such files, it needs to delete all but the most current 5. How often these files are create varies - can be every minute can be once a day, but it is important to leave the couple most current files. Conceptually I know what to do, but syntactically can't pull it off. Seems like it needs to do a ls -ltr (return the files in date order most recent being last). It needs to know how many were returned,. If it isn't more than 5, don't do anything else. If there are, get the files names of the all the logs except the last 5 returned by ls -ltr and delete them. But How to do all this?
ls -rt *.txt > tmp.tmp
wc -l tmp.tmp | read lines dummy
delcnt=0
[[ $lines -gt 5 ]] && delcnt=$(( lines - 5 ))
if [[ $delcnt -gt 0 ] ; then
while read rec
do
# chnge the echo to rm -f $rec
echo $rec
delcnt=$(( delcnt -1 ))
[[ $delcnt -eq 0 ]] && break
done < tmp.tmp
fi
Verify this works as required before you start deleting files
Thank you. Wow, I'd never have gotten to that elegant of a script.