How to delete only directories and leave files untouched

find . -maxdepth 1 -mindepth 1 -type d

then

find . -maxdepth 1 -mindepth 1 -type d -exec rm -rf '{}' \;

To add an explanation:

find starts in the current directory due to . and stays within the current directory only with -maxdepth and -mindepth both set to 1. -type d tells find to only match on things that are directories.

find also has an -exec flag that can pass its results to another function, in this case rm. the '{}' \; is the way these results are passed. See this answer for a more complete explanation of what {} and \; do


First, run:

find /path -d -type d

to make sure the output looks sane, then:

find /path -d -type d -exec rm -rf '{}' \;

-type d looks only for directories, then -d makes sure to put child directories before the parent.


To delete all directories and subdirectories and leave only files in the working directory, I have found this concise command works for me:

rm -r */

It makes use of bash wildcard */ where star followed by slash will match only directories and subdirectories.

Tags:

Unix

Directory

Rm