LOGO

Remove Subdirectories with One Linux Command

October 21, 2016
Remove Subdirectories with One Linux Command

Efficiently Removing Multiple Subdirectories in Linux

When needing to eliminate several subdirectories located within a parent directory using the Linux command line, it's common to employ the rm command repeatedly. However, a more streamlined approach exists to expedite this process.

A Faster Method Using Brace Expansion

Consider a scenario where a directory named 'htg' contains five subdirectories, and the intention is to delete three specific ones. Traditionally, this would necessitate executing the rm command three separate times.

Fortunately, the process can be significantly shortened by consolidating these multiple rm commands into a single, unified command.

To accomplish this, utilize the following command at the prompt, then press Enter. Remember to substitute the directory names with those you wish to remove.

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

The terms enclosed within the brackets constitute a "brace expansion list." Each element within this list is individually appended to the preceding path (~/Documents/htg/).

For instance, the example command expands to ~/Documents/htg/done, ~/Documents/htg/ideas, and ~/Documents/htg/notes. These represent the three subdirectories under 'htg' targeted for removal.

Understanding the -r Flag

The -r flag is essential when using the rm command to delete directories, as opposed to individual files. Omitting this flag will result in an error message indicating that the directories cannot be removed.

Alternative: Using rmdir for Empty Directories

If all the subdirectories you intend to remove are confirmed to be empty, the rmdir command provides a suitable alternative.

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

Should any of the subdirectories contain files or further subdirectories, an error message will appear, signaling the removal failure for that specific subdirectory and its contents. However, any empty subdirectories within the list will be successfully removed.

Important Caution

Exercise extreme caution when using the rm command. Incorrect usage can lead to the unintentional deletion of critical files from your hard drive.

Related: Learn how to efficiently create multiple subdirectories with a single Linux command.

It's also possible to generate a directory structure, including multiple subdirectories, using just one command.

#linux#command line#remove directories#delete subdirectories#file management#shell scripting