The other day, I encountered an issue involving three directories, and two of them contained a subdirectory with the same name (target).

My goal is to delete the target subdirectories in all places with a single command, and here’s the solution I found.

directory tree

Using the terminal to delete multiple directories.#

There is an useful command called find, this command is used to traverse nested directories and evaluate an expression for each element.

We can use find to delete files or directories, here is the command:

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

Understanding the command#

This command is easy to grasp, first we have ., this is telling find to start traversing in the current directory.

Next we have -type, this argument allows to select a a specific valid type.

The valid types are listed below:

  • b: block special
  • c: character special
  • d: directory
  • f: regular file
  • l: symbolic link
  • p: FIFO
  • s: socket

Since we need to find an specific directory we use d.

Next it’s -name, we need to give the string that contains the name we are searching for. In our case we are looking for the directories named "target".

The last part of the command, -exec, is telling what to do once we find a valid element. In this case we want to delete all the found occurrences, so we’re passing rm -rf.

The {} is just telling that we need to use the current element’s name, and + is used to terminate the -exec part.

Conclusion#

By using this simple command we can find and delete subdirectories in an easy and convenient way, which I find to be faster than using the GUI.

I hope this simple tutorial can help you to solve these kind of problems.