I usually use the command line bellow to remove directories on file system. But, for the 1st time find is returning names with white spaces on it, and rm doesn't recognize it.

find . -name .AppleDouble* -exec rm -rf {} \;

It throws the following error: find: './Aerosmith/Young Lust/.AppleDouble': No such file or directory

Is it possible to achieve it using just a single line like this one? Or should I use some kind of script? If the script is the solution, please, could you post an example?

  • 2
    @DavidSchwartz no, his command does not have that problem. His command would be equivalent to rm -rf 'foo /home' – stew May 3 '12 at 0:31

You want

find <whatever> -print0 | xargs -0 rm -rf

Contrary to what people will first assume is the problem, the problem you are having is NOT with the spaces in the filename. {} will correctly pass the filename to rm. The problem you are having is that find, by default is bredth first, not depth first. find has no idea what the rm command is doing, so after you rm, find is trying to then cd into the directory which you just removed, and you get a file not found error, because the directory it tries to cd into is gone.

@womble's answer works because it delays removing the directory. It will search through the directory for other things to remove from the directory first. This is not effecient, since its silly to look for files to remove in a directory if you are going to remove that entire directory anyway.

In GNU find, you can use the -delete action:

find . -name .AppleDouble* -delete

And find will be smart enough to do the right thing.

find . -name .AppleDouble* -exec rm -rf {} +

(using + instead of ; to terminate the comand) Is equivalent to @womble's command using xargs, it will have the effect of buffering actions until it scans the entire directory or runs out of room on the command line to rm, but it will suffer from the same problem in that it is uselessly searching for files to remove that are definitely going to be removed anyway.

  • 1
    It would also be advised to quote that *, or risk the shell expanding it if it were to ever match a file. Its obviously not the problem here, its just good practice. – Patrick May 3 '12 at 1:32

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.