Home > OS >  Linux - Can't recursively delete large directories
Linux - Can't recursively delete large directories

Time:10-21

I have a pretty big find that is supposed to delete any files/dir it finds. I just can't get it to work properly.

If I attach -exec rm -fr {} \;, at some point, I always get the following errors:

find: ‘/path/to/dir/file123.local’: No such file or directory

If I replace it with -delete, I get the following error:

find: cannot delete `/path/to/dir': Directory not empty

I looked for suggestions online but the suggestion is always the other option (replace -exec with -delete and vice-versa)

Does anyone happen to know a way to fix it without redirecting stderr to null?

Thanks ahead!

CodePudding user response:

find doesn't know what your command passed to -exec does. It traverses the directory tree in this order:

  1. find a file
  2. execute a command on that file
  3. if it's a directory, traverse it down

Now if the directory is removed with rm -fr, there is nothing to traverse down any more, so find reports it.

If you supply the -depth option, then the traversal order changes:

  1. find a file
  2. if it's a directory, traverse it down
  3. execute a command on that file

This will eliminate the error message.

-delete implies -depth, so ostensibly it should work. However it is your responsibility to make sure the directories you want to delete are completely cleaned up. If you filter out some files with -time etc, you may end up trying to delete a directory which is not completely clean.

CodePudding user response:

You could try to wrap {} in double quotes, there may have space in directry path.

-exec rm -rf "{}" \;

CodePudding user response:

If I read your question well, you want to remove files, but sometimes it happens that they already have been removed by some other process, and you wonder what you should do.
Why do you think you should do anything? You want the file to be gone, and apparently it is gone, so no worries.

Obviously the corresponding error messages might be annoying, but this you can handle adding 2>/dev/null at the end of your command (redirect the error output to <NULL>).

So you get:

find ... -exec rm -fr {} \; 2>/dev/null

Edit after comment from user1934428:

I might be a good idea to drop the r switch:

find ... -exec rm -f {} \; 2>/dev/null

In that case, you should have no errors anymore:

find ... -exec rm -f {} \;
  • Related