2

This question already has an answer here:

I create and keep the following automated backup files e.g.:

fruits_29-12-2013.gz
fruits_30-12-2013.gz
fruits_31-12-2013.gz
sweets_01-12-2013.gz
sweets_02-12-2013.gz
sweets_03-12-2013.gz

.. actually many of them in the same folder.

(But then it's a problem to house keeping them manually but I still have to. Because after a month, all are taken up the disk space. So I need to clean up the latest files, accordingly.)

How to automatically DELETE the OLDEST file with name starts with fruits?

(Then I'll put that script/command in the daily crons.)

marked as duplicate by Zelda, Anthon, rahmu, terdon, slm Jan 10 '14 at 12:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    I recommend you don't throw away the oldest file, if your backup process breaks without you noticing, deleting the oldest every day will gobble up your backups until they are all gone. Throw away any fruit_... file that is older than 30 days e.g. – Anthon Jan 10 '14 at 8:45
  • Do the date parts of the timestamps of the files ( ls -l ) match the date in the filenames? – Anthon Jan 10 '14 at 8:48
  • @Anthon - set -- ./fruits*gz; [ $# -gt 30 ] || exit 1; while [ -n "$2" ] ; do [ "$1" -ot "$2" ] && set -- "$@" "$1" ; shift ; done ; rm -- "$1" – mikeserv Aug 5 '14 at 4:37
2
rm  "$(ls -1t fruits_*.gz | tail -1)"

The above gets the names of files, one per line, sorted by age (ls -1t) and deletes (rm) the last, that is, oldest, one (tail -1).

(The above would not work for all files, but since your files are sensibly named, it will be fine.)

Another possibility, as per @Anthon's comment, is to delete backups that are older than, say, 30 days. In that case:

find . -maxdepth 1 -mtime +30 -name 'fruits_*.gz' -delete

The above deletes files found in the current directory (.) but not deeper (-maxdepth 1) with the last modified time of over 30 days ago (-mtime +30) and a name which matches the pattern fruit_*.gz.

Both of the above commands assume that the current working directory is the one with the backup files. You can run them from another directory with minor changes.

  • Perfect and easier then i expected honestly!! Only this is more then enough: find . -maxdepth 1 -mtime +30 -name 'fruits_*.gz' -delete Thanks!!! – 夏期劇場 Jan 10 '14 at 9:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.