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:
- Get Directory of Bash Script Being Executed
- URL Escape Strings in Google Spreadsheets with a Simple Script
- Ignoring pyc and other file patterns in Subversion
About this entry
You’re currently reading “Bash Script to Cron for Deleting Old Log Files,” an entry on experiments and essays
- Published:
- 7.27.09 / 12pm
- Category:
- command line

View Comments
Jump to comment form | comments rss [?]