How to Remove a Directory in Linux?

In Linux, removing a file or directory is a basic operation that any Linux user needs to learn; however, it seems simple, but it has different methods, each with its specific use cases.

In Linux, when working with directories, the way of removing depends on whether the directory contains content or not. If the directory contains content, removing it with the rm command without using the -r flag will not proceed.

By following this guide, you will learn how to delete a directory in Linux VPS, which will enable you to remove unneeded and unnecessary files and directories in your Linux Server with recursive, interactive, and forced mode.

List Files and Directories in Linux

In a Linux server environment, unlike Windows, which has an easy to use graphical interface that allows you to manage files and directories with a few clicks, you need to first verify whether the directory contains any content, then decide which method to use.

To list directories in Linux, you can use multiple commands; here you can see the easiest and most useful ones.

List All Files in a Directory and Subdirectory in Linux

The ls command shows the directory names and files in the current directory. To list all the subdirectories and files, you can use the ls command with the recursive flag (-R), which lists all things recursively.

ls -R /directory_address

Or, for getting better and structured output, you can use this command in the location you want to get a list of its contents:

tree

list files and directories in linux with tree command

Delete an Empty Directory in Linux

To remove a directory on Linux, the rmdir command is used, which is a simple method to delete directories without content. But if the directory contains any content, the action will not proceed.

rmdir Directory_Name

Replace your directory name with Directory_Name in the command above and use the delete directory command.

rmdir has many options (flags) that can be useful while using it. You can see these options alongside their description:

commandDescription
rmdir -p directory_nameRemoves the specific directory and its parent if it becomes empty after removal
rmdir -v directory_nameDisplays a message for each directory that is succesfuly removed. This is useful for seeing which directories are removed.
rmdir --ignore-fail-on-non-empty directory_nameIgnores errors caused by non-empty directories and continues processing other directories. It does not remove non-empty directories.
rmdir --helpDisplays the help message and provides information about the available rmdir options

If you try to remove a non-empty directory with rmdir, you will see this error:

rmdir: failed to remove 'directory_name': Directory not empty

This happens because removing data containing content or data accidentally could result in losing important files. Linux requires the user to explicitly tell the system that you want to remove the directory’s content too.

Delete a Non Empty Directory in Linux

To remove a non-empty directory, Linux provides several methods depending on your requirements, like recursive, interactive, forced, and selective deletion methods.

Warning: Before removing any directory’s content, list its content as told in the previous section to understand what files you are removing; don’t blindly remove anything.

And make sure to back up your Linux Server before starting the removal because the rm command removes everything permanently. That means there is no way to restore it, or it’s very hard, so take a backup to avoid regrets.

Delete Folder Recursively in Linux

The standard method for removing a non-empty directory is to use the Linux rm directory command with the recursive option:

rm -r directory_name

or you can use:

rm --recursive directory_name

This command tells the system to open the main directory, enter all subdirectories, remove every file, empty directories and subdirectories in them, and then remove the main directory itself too.

Remove Directory with Force in Linux

In Linux, doing an action with force means it does this action without asking for confirmation, and ignores missing files or any errors in the process.

Here, force removal removes everything:

rm -rf directory_name

Force removal is mostly used by administrators to manage files more easily without dealing with errors, but it should be used with caution.

Remove Directory Interactively in Linux

To clean directories, you have another option that is called interactive removal, which, when removing a directory with its contents, during the removing proccess it asks for confirmation to remove each file or directory. Here you can see a real example in the image below:

1- First, list directories with the tree command

tree /directory_name

2- Run the interactive directory removal command:

rm -ri directory_name

remove directory interactively in linux

Delete Specific Files in a Directory in Linux

Sometimes you don’t want to remove the whole directory, and you want to remove some specific files in a directory. You just need to specify the file type extension that you want to remove, which you can find in the table below:

File TypesExtensions
Image.jpeg | .jpg | .png | .webp | .tiff | .gif
Video.mp4 | .mov | .mkv | .webm | .avi
Audio.mp3 | .flac | .wav | .aac | .ogg
Document.docx | .doc | .txt | .rtf | .odt | .xlsx | .pptx | .pdf
System File.sh | .conf | .tar.gz | .deb | .rpm | .so | .log

Here, in the command below, replace the extension name you want.

rm directory_name/*.extension

Delete Content But Keep Directory on Linux

If you want to keep the directory itself and remove all other files, you should use the command below:

rm --no-preserve-root directory_name/*

In the previous section, you were specifying the file extensions, which removes files with this extension only, but this command removes all files and directories in a folder.

Note: Make sure you use –no-preserver-root to keep the directory and remove files

Note: This previous command does not remove hidden files like (.env, .git, .htaccess). To remove these files too and make the Linux folder fully empty, use this command

rm -rf directory_name/* directory_name/.[!.]* directory_name/..?*

The rm command has many options for removing directories and files; you’ve seen useful and most used ones in sections above, and you can see some others which can be useful for your need in the table above:

rm Command flagsExampleDescription
-i or --interactiverm -i file.txtPrompts the user for confirmation before deleting each file, helping prevent accidental removal.
-r or --recursiverm -r directory_nameRecursively deletes a directory and all its contents, including subdirectories and files.
-f or --forcerm -rf directory_nameForces deletion without prompting for confirmation and ignores non-existent files or errors. Does not override file permissions.
--preserve-rootrm --preserve-root -rf /Prevents rm from deleting the root directory (/) and its contents, even if explicitly requested.
--interactive=oncerm --interactive=once file1.txt file2.txtPrompts for confirmation once before deleting multiple files, providing a balance between safety and convenience.
-v or --verboserm -rv directory_nameDisplays detailed information about each file and directory being removed. Useful for tracking actions.
--helprm --helpShows the help message with usage instructions for the rm command.
--versionrm --versionDisplays the installed version of the rm command.

Find and Delete Directory on Linux

Removing specific files considering their names and types manually by the methods above is hard and time-consuming. To manage files more easily and efficiently, you can use the find command in Linux, whether you are cleaning up storage, removing temporary files, or organizing folders in the Linux system.

Find Directory in Linux

Linux provides the find tool, which is a flexible tool for searching for files and directories in Linux based on name, type, size, modification time, etc.

syntax:

find [path] [options] [expression]

Example:

find /var/log -name "*.log"

This command finds all log files in the “/var/log” directory.

Searching for files with the find command is an advanced skill that, if you want to manage files for an FTP server or troubleshoot your system files, knowing how to search for files in Linux helps you to manage everything more easily and saves you a lot of time.

Delete Directories With Find in Linux

You can combine the find command with deletion to find and remove files or directories that match a specific criteria.

Delete Files by Name:

find . -type f -name "*.tmp" -delete

This command searches for all .tmp files in the current directory and removes them immediately.

Delete Directories by Name

find . -type d -name "cache" -exec rm -rf {} +

This command finds all directories named cache and removes them along with their contents.

Note: Before deleting files, always test your commands without the -delete or -exec rm option to see the output that you will delete. This action allows you to verify which files are getting removed and ensures you won’t lose anything important.

Conclusion

Removing a directory and cleaning up its content is a basic and simple Linux skill that every administrator and normal user must understand. It is simple, but all deletion actions should be done with caution to prevent removing important data on the server.

To remove empty directories, you can use the rmdir command, which is designed for removing directories in Linux systems, or you can use the rm command, which is more powerful, and by using its flags (options), you can have more flexibility.

There are more advanced ways, like using find and remove commands together to locate and remove files and directories based on some criteria. It can be used for automation and managing large-sized systems.

By mastering these methods, you can manage files in your Linux server efficiently, but keep in mind that talking backup is always should be the first step.

FAQ

1. How to Recover Deleted Files in Linux?

If you removed a file with the rm command, your files can be restored if they didn’t get overwritten.

The rm command removes files permanently, but the data still exists on data until they get overwritten. You can try using (testdisk, extundelete, debugfs, photorec), which can help you to recover your files.

2. Cannot Remove Directory in Linux

When removing a directory in Linux, you can get the “rm: cannot remove ‘mydir’: Device or resource busy” error if the directory is currently being used, mounted, or another process is accessing it. Make sure you are out of the directory and try removing it again.

cd ..

And you can use -f flag to force cleanup.

rm -rf /directoryName


author image

The Author Richard.M

Richard started out as a member of the support team and is now a full-stack web developer and support team lead at VPS Makers. He is passionate about providing people with top-notch technical solutions based on his 5 years of experience in web hosting, but as much as he enjoys coding and creating new works, he secretly dreams of becoming a sports star.

More from Richard.M

Post Your Comment

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