Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am using the following command to delete old backup files:

find backups/ -name "bak_*.tbz" -mmin +4800 -exec rm -vf {} \;

The problem: When there are no new files, than all files are deleted. I would likke to keep the newest one in such case.

What is an elegant way to delete old files except the newest one?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted
 find  backups/ -name "bak_*.tbz" -mmin +4800 -type f -printf '%T@ %p\n' | sort -k 1nr |\
      tail -n +2 | cut -d ' ' -f 2 | xargs echo rm {}

This assumes GNU find and will print the modification time and file name, sort this by the mod time, delete the first line (newest file), remove the mod time column and hand this over to xargs for deletion (as stated, it will only echo the delete command, not actually do it).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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