It’s hard to explain in the title.
I have a bash script that runs daily to backup one folder into a zip file. The zip files are named worldYYYYMMDD
.zip with YYYYMMDD
being the date of backup. What I want to do is delete all but the 5 most recent backups. Sorting the files alphabetically will list the oldest ones first, so I basically need to delete all but the last 5 files when sorted in alphabetical order.
Advertisement
Answer
The following line should do the trick.
ls -F world*.zip | head -n -5 | xargs -r rm
ls -F
: List the files alphabeticallyhead -n -5
: Filter out all lines except the last 5xargs -r rm
: remove each given file.-r
: don’t runrm
if the input is empty