Managing files and folders (directories) from the command line is an essential skill for any Linux user. While creating a new directory is straightforward (using mkdir), deleting one requires a bit more care. Unlike a graphical interface where deleted folders go to a “Recycle Bin,” deleting a directory in the Ubuntu Linux terminal is generally permanent. The primary tool for this job is the rm (remove) command, but it must be used with specific flags to work on directories.
Attempting to Remove a Directory (The Error)
If you have a directory named “old_project” and you simply try to use the standard remove command:
rm old_project
Ubuntu will return an error message: rm: cannot remove 'old_project': Is a directory. This happens because, by default, rm is designed as a safety measure to only delete individual files, preventing you from accidentally wiping out an entire folder full of important data with a simple typo.
How to Remove an Empty Directory (rmdir)
If the directory you want to delete is completely empty (it contains no files and no sub-directories), you can use the specialized rmdir (remove directory) command.
rmdir old_project
If the folder is truly empty, this command will delete it silently and return you to the prompt. If there is even a single hidden file inside, rmdir will fail and warn you that the directory is not empty.
How to Remove a Directory and All Its Contents (rm -r)
Most of the time, you want to delete a directory that contains files, code, or other folders. To do this, you must tell the rm command to operate recursively. This means the command will dive into the directory, delete every file inside it, delete any sub-directories, and finally delete the main directory itself.
You do this by adding the -r (recursive) flag:
rm -r old_project
This command will delete the directory and everything inside it. If you have hundreds of files inside, it will process them instantly.
Using the Force Flag for Stubborn Files (rm -rf)
Sometimes, when you use rm -r, the terminal will pause and prompt you for confirmation to delete certain write-protected files within the directory. If you are absolutely certain you want to delete the directory and everything in it without being interrupted by confirmation prompts, you can add the -f (force) flag.
rm -rf old_project
WARNING: The rm -rf command is incredibly powerful and dangerous. It will instantly and permanently obliterate the specified directory and all its contents without a single warning. If you accidentally run rm -rf / (which attempts to delete the entire root file system), you will destroy your Ubuntu installation. Always double-check your spelling before pressing Enter when using the -rf flags.