Bash Script to Cron for Deleting Old Log Files

27 Jul 2009

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

Let's talk

I'm one of the founders of Venmo. If you liked this essay/experiment -- or didn't -- @ me.