If you want to remove several subdirectories within another directory using the command line in Linux, generally you have to use the rm command several times. However, there is a faster way to do this.

Let’s say we have a directory called htg with five subdirectories within it and we want to delete three of them. In a normal situation, we’d use the rm command three times.

However, we can make this process even shorter by combining the three rm commands into one. Here’s how.

To remove the three subdirectories you only need to type the following command at the prompt and press Enter (obviously, change the directory names to what you want to remove).

rm -r ~/Documents/htg/{done,ideas,notes}

The words in the brackets are part of the “brace expansion list”. Each of the items in the brace expansion list is appended separately to the preceding path (~/Documents/htg/). For example, the above command is expanded into ~/Documents/htg/done, ~/Documents/htg/ideas, and ~/Documents/htg/notes, the three subdirectories under the htg directory that we want to remove. As you can see in the screenshot below, those three subdirectories were removed.

The -r flag is required when using the rm command to remove a directory rather than a file. If you leave the -r flag out of the above command, you will get an error saying that the directories cannot be removed.

If all of the subdirectories you want to remove are empty, you can use the rmdir command, as shown below.

rmdir ~/Documents/htg/{done,ideas,notes}

If it turns out that any of the subdirectories are not empty, an error will display saying that the removal failed and the subdirectory in question and its subdirectories are not removed. However, any empty subdirectories are removed.

Be very careful with the rm command. Using it the wrong way can delete all the files on your hard drive.

RELATED: 8 Deadly Commands You Should Never Run on Linux

You can also create a directory containing several subdirectories, or a directory tree, using one command.

Profile Photo for Lori Kaufman Lori Kaufman
Lori Kaufman is a technology expert with 25 years of experience. She's been a senior technical writer, worked as a programmer, and has even run her own multi-location business.
Read Full Bio »