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.
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'):
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:
and then deletes files except for the last seven created:
If the above folder does not exist then the code after && will not execute.