deleting folders with spaces in their names using xargs [duplicate]

Fix it using -print0 in find and xargs -0 in xargs to tell both commands to use the NULL character as a separator instead of space:

find . -type d -print0 | xargs -0 rm -rf

Here's a nice explanation of why it breaks and how this fix works from The Linux Command Line by William E. Shotts Jr.

Dealing With Funny Filenames

Unix-like systems allow embedded spaces (and even newlines!) in filenames. This causes problems for programs like xargs that construct argument lists for other programs. An embedded space will be treated as a delimiter, and the resulting command will interpret each space-separated word as a separate argument. To overcome this, find and xarg allow the optional use of a null character as argument separator. A null character is defined in ASCII as the character represented by the number zero (as opposed to, for example, the space character, which is defined in ASCII as the character represented by the number 32). The find command provides the action -print0, which produces null-separated output, and the xargs command has the --null option, which accepts null separated input. Here’s an example:

find ~ -iname '*.jpg' -print0 | xargs --null ls -l

Using this technique, we can ensure that all files, even those containing embedded spaces in their names, are handled correctly.

(-0 is the short version of the --null option)


You don't need xargs, find itself can do it robustly with handling:

  • any kind of possible filenames

  • without triggering ARG_MAX

If the directories are empty, use -delete action:

find . -type d -delete

If not empty, use rm -r in the -exec action:

find . -type d -exec rm -r {} +

If you insist on using xargs, for any directory names without newline in their names you can use newline as the delimiter of incoming arguments:

find . -type d | xargs -d $'\n' rm -r

Best way, get files NUL separated and deal with it with -0 option of xargs:

find . -type d -name 'foo bar*' -print0 | xargs -0 rm -r

For all the rm -r used, add -f i.e. do rm -rf if needed.


To specifically delete all subdirectories having spaces in their name, the simplest command would be :

find . -type d -name "* *" -exec rm -rf {} +

This is the same approach as the one heemayl already suggested, the only difference being the -name filtering.