What do you think? Discuss, post comments, or ask questions at the end of this article [More about me]

On a 'nix machines (example here is on an Ubuntu service 16.04 server) you may want to delete all files in a folder except for the last "x" created files.

This can come in handy when for deleting older files in an automated backup directory for example.  See below for an example of this use case.

Guide

My confluence setup creates a restorable backup of confluence data every morning at 2am to /var/atlassian/application-data/confluence/backups/.  This folder can get quite large with lots of backups.  I'm really only interested in keeping the 7 backups.

I added the below line to my crontab (run 'sudo crontab -e'):

# Confluence backups - only keep last 7 backups (confluence backups are done at 2am every morning from confluence )
0 3 * * * cd /var/atlassian/application-data/confluence/backups/ && ls -1tr | head -n -7 | xargs -d '\n' rm -f --

This runs every morning at 3am (backups at 2am) and deletes all backups except for the last 7 created. 

This code simply changes to the backup folder:

cd /var/atlassian/application-data/confluence/backups/

and then deletes files except for the last seven created:

ls -1tr | head -n -7 | xargs -d '\n' rm -f --

Note

If the above folder does not exist then the code after && will not execute.