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.

02_removing_subdirectories_separately

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.

03_removing_three_subdirectries_at_once

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.

04_cannot_remove_subdirectory

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.

05_using_rmdir_command

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

Related: How to Create Multiple Subdirectories with One Linux Command

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