Home > All, Linux > Be careful when using find with the delete flag to clean old files.

Be careful when using find with the delete flag to clean old files.

The linux find command is very powerful. I use it all the time, either manually or in cron scripts to delete useless Thumbs.db files for example. A word of caution however, if you intend on using the -delete flag with find (instead of -exec rm… or xargs etc.).

This is very bad:

find / -delete -type f -name 'Thumbs.db' -mtime +7

This is good:

find / -type f -name 'Thumbs.db' -mtime +7 -delete

The order of the -delete flag is very important. In the first case find will delete everything it finds (totally ignoring the subsequent criteria), whereas the second case will delete what is matched.

In other words, the order of the find flags/parameters/actions are very important. If you are in doubt, or even if you are not, you should always have a backup in case something goes wrong.

CentOS help for -delete flag:

Delete files; true if removal succeeded. If the removal failed, an error message is issued. Use of this action automatically turns on the ’-depth’ option.

Fedora help for -delete flag:

Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find’s exit status will be nonzero (when it eventually exits). Use of -delete automatically turns on the `-depth’ option.

Warnings: Don’t forget that the find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. When testing a find command line that you later intend to use with -delete, you should explicitly specify -depth in order to avoid later surprises. Because -delete implies -depth, you cannot usefully use -prune and -delete together.