3

Found a few similar questions but were not quite a match.

I have a directory for backups (sql) and want to delete all files in that directory older then 7 days leaving any sub-directories intact.

This is what I have:

find /var/log/mbackups -mtime +7 -type f -delete

Is this the proper way to accomplish what I am after?

  • 1
    What do you mean by "leaving any sub-directories intact"? Do you mean "don't delete files from sub-directories" or do you mean "don't delete the sub-directories themselves"? – Kusalananda Jun 1 '18 at 17:03
  • Note the gotcha about -mtime +N. With GNU find, -mtime +7 will find files that are at least eight days old. – ilkkachu Jun 1 '18 at 17:07
2

Your command will look at the top level directory /var/log/mbackups and also descend into any subdirectories, deleting files that match the seven day criterion. It will not delete the directories themselves.

If you want a command to look at files only in the /var/log/mbackups directory, and not descend into subdirectories, you need to add that restriction:

find /var/log/mbackups -maxdepth 1 -mtime +7 -type f -delete

In general you can test the find command by replacing the -delete action with something innocuous, like -print:

find /var/log/mbackups -mtime +7 -type f -print
-3

Warning: -delete is non-standard (nonportable) and risky when using gfind.

Remember that rm is forbidden to remove any file that starts with ./or .. for security reasons, but the gfind man page does not mention such a restriction. I therefore recommend to use the official method:

find /var/log/mbackups -mtime +7 -type f -exec rm {} +
  • 1
    rm will happily delete a file beginning with ./, for example touch xx; rm ./xx – roaima Jun 6 '18 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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