Bash Script to Cron for Deleting Old Log Files

Here is a little bash script I wrote to allow a max of N log files in a given directory. I looked for awhile for something similar to this and could not find anything, so I thought I would share in case anyone else had the same problem.

The example here will delete all but the most recent 40 files in a directory. The script assumes files are named chronologically with the oldest files so that an alphabetical sort orders the files with the oldest at the top.


MAX_FILES=40
TOTAL_FILES=`ls -1 | wc -l`
NUM_FILES_TO_DELETE=`expr $TOTAL_FILES - $MAX_FILES`
if [[ $TOTAL_FILES -gt $MAX_FILES ]]; then ls -1 | head -n $NUM_FILES_TO_DELETE | xargs rm; fi

Related posts:

  1. Get Directory of Bash Script Being Executed
  2. URL Escape Strings in Google Spreadsheets with a Simple Script
  3. Ignoring pyc and other file patterns in Subversion
You should follow me on Twitter here.
Subscribe to labs via email here.

About this entry