How to Delete a Non-Empty Directory Using the rm Command

March 2, 2024 / Command Line

In this article, we explain how to delete a non-empty directory in Linux using the rm command. Since rm is a powerful command that permanently removes files and directories, it should be used with caution.

Understanding the rm Command
The rm command is mainly used to remove files, but with the proper options, it can also delete directories and their contents.

Basic Syntax

rm [OPTION] FileOrDirectoryName

By default, rm does not remove directories. You must use specific options to do so.

Common rm Options (with Full Forms)
Below are the commonly used rm options for deleting directories, along with their full forms and explanations:

  • -r, -R, –recursive
    Removes directories and their contents recursively (including all files and subdirectories).
  • -f, –force
    Ignores nonexistent files and arguments, and never prompts for confirmation.
  • -d, –dir
    Removes empty directories only.
  • -i
    Prompts for confirmation before every removal.
  • -I
    Prompts once before removing more than three files or when removing directories recursively (less intrusive than -i).
  • -v, –verbose
    Displays details of what is being removed.
  1. Delete a Non-Empty Directory
    To remove a directory along with all its contents, use the recursive (-r) option.
    Example:
    rm -r Simple-Directory
    This command deletes Simple-Directory along with all its subdirectories and files.
  2. Delete Without Confirmation
    If the directory or files are write-protected, Linux will prompt for confirmation. To delete a directory without any prompts, use the force (-f) option along with -r.
    Example:
    rm -rf Simple-Directory
  3. Delete an Empty Directory Using rm
    You can also use the rm command to delete empty directories by specifying the -d (–dir) option.
    Example:
    rm -d Simple-Directory
  4. Delete Multiple Directories
    Like the rmdir command, rm can delete multiple directories at once.
    Example:
    rm -r Directory_1 Directory_2 Directory_3

Important Warning: Exercise extreme caution when using the rm command, especially with the -r and -f options. Once deleted, files and directories cannot be recovered unless you have a backup in place. Always double-check the directory path and ensure you are executing the command in the correct location.

By following the steps above, you can safely delete non-empty directories using the rm command. For additional assistance, feel free to contact our support staff.

Managing files on Linux servers?
For full control over file systems and commands, consider using a Linux VPS environment with root access.
Spread the love