Command Linux

How to Remove a Non-Empty Directory in Linux

In Linux, whenever you want to delete a file, you’d use the rm command. When it comes to deleting a directory, however, things get a bit complex. To delete a directory, there’s a dedicated tool rmdir that can remove empty directories. What if the target directory contains a bunch of unnecessary files?

In this guide, check out how to remove non-empty directories in Linux.

Removing a Directory in Linux

First, let’s have a look at how to remove directories in Linux.

Removing an Empty Directory

In this example, I have set an empty directory:

$ tree <dir>

To remove the directory, we can use rmdir:

$ rmdir <dir>

Removing a Non-Empty Directory

When it comes to a non-empty directory, the previously mentioned methods won’t work.

Here, I’ve set a non-empty directory for demonstration:

$ tree <non_empty_dir>

Try to remove normally, use the following command:

$ rmdir <non_empty_dir>

$ rm <non_empty_dir>

To remove the non-empty directory, use the following rm command instead:

$ rm -vr <non_empty_dir>

Here:

  • -r: Instructs rm to recursively delete the contents of the directory, both the files and sub-directories.
  • -v: Instructs rm to run in verbose mode.

If you don’t want any prompt for action, then add the flag “-f”, as well:

$ rm -vrf <non_empty_dir>

If you want to have prompts for actions, then use the flag “-i” instead. Note that rm will ask for all the files and sub-directories it’s about to remove:

$ rm -vri <non_empty_dir>

Instead of “-i”, the flag “-I” is less intrusive while still protecting against mistakes:

$ rm -vrI <non_empty_dir>

Conclusion

In Linux, removing a directory is different than removing files. The removal tools and methods are also different depending on whether the target directory is empty or not. This guide demonstrates how to remove both empty and non-empty directories. Note that the directories and the data contained within and removed in this manner will have no way of being recovered except by using special tools and methods. Thus, before removing, ensure that it’s not something important.

The man pages of rm and rmdir contain further information about various supported options:

$ man rm

$ man rmdir

Related Articles

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Back to top button