Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Keep 5 most recent files in a directory

One can keep the most recent n files in a directory with just three shell programs: ls, tail, and xargs.

Here is an example to use in a nightly database backup cron job:

# Keep last 5 files ending in .dump
# Don't forget to 

# Installation
# 1. cp /usr/local/bin/
# 2. chmod u+x /usr/local/bin/
# 3. Set the DB variable
# 4. Set the BACKUP_DIR variable

# Example usage for cron to run at 4:05 am every day:
# 5 4 * * * /usr/local/bin/


DATE=$(date "+%Y-%m-%d_%H%M")
pg_dump -Fc $DB > $BACKUP_DIR/$DATE.dump

/bin/ls -t $BACKUP_DIR/*.dump | tail +6 | xargs rm