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

July 3, 2024 / General Discussion

In Linux, deleting directories is a popular file system management job, especially when clearing out unnecessary files and directories. The rm command is used with options when working with a non-empty directory to guarantee that all contents including files and subdirectories are deleted. This guide will assist you in deleting a non-empty directory using the rm command.

The rm command will permanently remove files and directories without asking for confirmation, so be alert while using it.

Steps to Delete a Non-Empty Directory 

  1. Open your terminal:
    Launch the terminal that you prefer (e.g., Terminal, Konsole).  
  2. Navigate to the directory:
    Use the rm command to find the non-empty directory.
    rm option FileOrFolderName 
  3. Delete the non-empty directory:
    To remove the directory and its contents, use the rm command with the -r (recursive) option.
    rm -r current_directory
    Often used to suppress prompts and error messages is the -f (force) option:
    rm -rf current_directory
    The -d option is required to remove empty directories.
    rm -d current –Directory
    rm can also be used to delete several folders. In the command line, add the directory names as new arguments:
    rm -r Directory_1 Directory_2 Directory_3 
  4. Verify deletion:
    To confirm that the directory deleted, list the items in the parent directory:
    ls
    Let’s say you have a directory called backup that isn’t empty and is in your home directory (/home/user)
  5. Launch the terminal. 
  6. Navigate to your home directory:
    cd /home/user
  7. Run the rm command:
    rm -rf backup
  8. Verify the deletion:
    ls

You can use the rm command to safely remove non-empty folders by following these procedures. Always double-check the directory path and contents before executing the command to prevent accidental data loss. If you have any questions or need further assistance, reach out to our support team. 

Learn more in “How to Eliminate Non-Empty Directories in Linux” for methods and tips on removing directories with contents.

Leave a Reply

Your email address will not be published. Required fields are marked *