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

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
| improve this answer | |

try this

find /var/log/mbackups -type f -mtime +7 -exec rm -rf {} \;
| improve this answer | |
  • Any reason why you would use that instead of the command in the question? Note that the question asks "is this the proper way?", not "are there any other ways?". – Kusalananda Apr 15 at 10:48

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

Remember that rm has some security restrictions, but the gfind man page does not mention such a restrictions for -delete. I therefore recommend to use the official method:

find /var/log/mbackups -mtime +7 -type f -exec rm {} +

This is not even slower than the non-standard method using -delete.

| improve this answer | |
  • 2
    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.