How to Remove a Directory in Linux – Delete a Folder Command

Deleting directories is a fundamental skill for any Linux user, whether you‘re a beginner, software developer, system administrator, or data scientist. In fact, a recent survey of over 32,000 Linux users found that file and directory management are among the top 3 most frequent tasks.1

But with powerful commands like rm lurking on the command line, you might feel hesitant to start deleting directories willy-nilly. In this in-depth guide, we‘ll conquer the fear and mystery around directory deletion in Linux. When you‘re finished reading, you‘ll be wielding rm and rmdir with confidence and precision. Let‘s get started!

Why Delete Directories in Linux?

You might be wondering, why bother deleting directories at all? Can‘t I just keep everything forever? Well, while storage is cheaper than ever these days, a tidy filesystem is still important for performance, organization, and your own sanity.

Over time, leftover directories from old projects, experiments, and temporary files can really pile up. Deleting them frees up disk space and declutters your environment. It‘s like Marie Kondo for your computer – discard what no longer serves you.

For example, a machine learning project might generate gigabytes of intermediate files during training and evaluation. Once you‘ve saved the final model, those directories full of checkpoints and logs aren‘t doing much except taking up space.

Or perhaps you have directories full of old website assets that have since been refactored or moved to a CMS. No need to let those zombies haunt your server for eternity.

Even small directories can add up over time. A data analysis in R or Python might create hundreds of tiny intermediate files and plots. Deleting the cruft can speed up your workflow and help you focus on what‘s important.

Meet rm and rmdir

In Linux, the two main commands for deleting directories are rm and rmdir.

rm is a general-purpose tool for deleting both files and directories. By default, it doesn‘t delete directories – you have to specify the -r or -R option to recursively delete a directory and all its contents.

rmdir, on the other hand, is a more specialized tool that only deletes empty directories. If a directory contains any files or subdirectories, rmdir will throw an error.

Here are the basic usages:

# Delete a file
rm file.txt

# Delete an empty directory 
rmdir empty_dir

# Recursively delete a directory and its contents
rm -r full_dir

At first glance, rmdir might seem a bit pointless. Why not just always use rm -r? The key is that rmdir acts as a safety net. It prevents you from accidentally deleting a non-empty directory, which could have serious consequences.

Imagine you had a script that used rm -r to clean up some temporary directories. If a bug caused the wrong directory to be passed in, you could accidentally wipe out something important. Using rmdir instead would cause the script to fail safely if the directory wasn‘t empty.

Deleting Directories Step-by-Step

Now that you know the basics of rm and rmdir, let‘s walk through the process of deleting a directory step-by-step. We‘ll cover both empty and non-empty directories.

Step 1: Check the Contents

Before you delete a directory, it‘s a good idea to check what‘s inside it. You can use the ls command to list the directory contents:

ls my_directory

If my_directory is empty, you‘ll see no output. If it contains files and subdirectories, you‘ll see something like:

file1.txt
file2.jpg
subdir1/
subdir2/

Step 2: Confirm the Deletion

Double check that you really want to delete the directory and its contents. Remember, Linux doesn‘t have a "trash bin" or built-in undo button. Once a directory is deleted with rm or rmdir, it‘s gone for good (barring some advanced data recovery techniques).

If you‘re not sure, you can use the -i option with rm to confirm each deletion:

rm -ri my_directory

This will prompt you to confirm the deletion of each file and subdirectory:

rm: descend into directory ‘my_directory‘? y
rm: remove regular file ‘my_directory/file1.txt‘? y
rm: remove regular empty file ‘my_directory/file2.jpg‘? y
rm: descend into directory ‘my_directory/subdir1‘? y
rm: remove regular empty file ‘my_directory/subdir1/file3.txt‘? y
rm: remove directory ‘my_directory/subdir1‘? y
...

Step 3: Delete the Directory

If the directory is empty, you can use rmdir:

rmdir my_directory

If the directory contains files and subdirectories, use rm -r:

rm -r my_directory

And that‘s it! The directory is now deleted.

Advanced Directory Deletion

In addition to the basic rm and rmdir usage, there are some more advanced techniques to know about.

Deleting Directories with Special Characters

If a directory name contains spaces or special characters, you need to either quote the name or escape the characters:

# Quoting
rm -r "My Directory"

# Escaping 
rm -r My\ Directory

This is a common gotcha for beginners. Without quoting or escaping, the shell would interpret the space as an argument separator and try to delete two separate things: My and Directory.

Deleting Directories with Restrictive Permissions

By default, you must have write permission on a directory to delete it. If you try to delete a read-only directory, you‘ll get a "Permission denied" error:

rmdir read_only_dir
# rmdir: failed to remove ‘read_only_dir‘: Permission denied

To delete a read-only directory, you need to first change its permissions with the chmod command:

chmod +w read_only_dir
rmdir read_only_dir

Deleting Large Directories

Deleting large directories can take a while, especially if they contain many small files. For example, a 2 GB directory with 100,000 files will take longer to delete than a 2 GB directory with only 10 files.

That‘s because rm has to individually unlink each file from the filesystem before it can delete the directory itself. The more files, the more work rm has to do.

If you‘re deleting a very large directory, it can be helpful to use the -v verbose option to see progress:

rm -rv large_directory

This will print each file and subdirectory as it‘s being deleted.

Deleting Multiple Directories

You can delete multiple directories at once by passing them as separate arguments to rm or rmdir:

# Multiple empty directories
rmdir dir1 dir2 dir3

# Multiple non-empty directories
rm -r dir1 dir2 dir3

Be careful when deleting multiple directories, as it‘s easier to accidentally include one you didn‘t mean to. Always double check the list of directories before running the command.

Deleting Directories Across Filesystems

By default, rm will not delete directories that are on a different filesystem from the one you‘re currently on. This is a safety measure to prevent accidentally deleting mounted drives or network shares.

For example, let‘s say you have an external hard drive mounted at /mnt/external. If you tried to recursively delete /mnt, rm would stop at /mnt/external:

rm -rf /mnt
# rm: cannot remove ‘/mnt/external‘: Invalid argument

To override this behavior and allow rm to cross filesystem boundaries, use the --one-file-system option:

rm -rf --one-file-system /mnt

This can be useful if you really do want to delete everything, but be extra careful. There‘s no turning back once those directories are gone.

Under the Hood: How rm and rmdir Work

So what‘s actually happening when you delete a directory with rm or rmdir? It‘s not as simple as just erasing the directory from disk.

In Linux, directories are implemented as a special type of file that contains a list of the files and subdirectories it contains. Each file and subdirectory has an entry in the directory file called an inode.

When you delete a file with rm, it removes the file‘s inode entry from the directory file and marks the file‘s data blocks as free space. The file‘s contents aren‘t actually erased, but without an inode pointing to them, they‘re effectively gone.

Deleting a directory is similar, but with an extra step. First, rm recursively deletes all the files and subdirectories inside the directory. Once the directory is empty, rm can delete the directory file itself by removing its inode entry from the parent directory.

rmdir works the same way, but skips the recursive deletion step. If the directory isn‘t already empty, rmdir will exit with an error.

This process of unlinking files and directories from the filesystem is why deleting large directories can take some time. rm has to traverse the entire directory tree and unlink each file and subdirectory individually.

It‘s also why recovering deleted files in Linux is difficult. Once the inode is gone, the file‘s data is no longer reachable by normal means. Special data recovery tools can sometimes scan the raw disk for leftover data, but it‘s not guaranteed.

Deleting Directories in Other Operating Systems

If you‘re coming to Linux from another operating system, you might be used to a different way of deleting directories.

On macOS, the rm command works similarly to Linux. The main difference is that macOS has a built-in "Trash" folder where deleted files go by default. To bypass the Trash and delete a directory immediately, use the -f option:

rm -rf directory

In Windows, the command for deleting a directory is rmdir or rd:

rmdir directory
rd directory

Like Linux, Windows requires the directory to be empty before it can be deleted. To recursively delete a directory and its contents, use the /s option:

rmdir /s directory
rd /s directory

Deleted files in Windows go to the "Recycle Bin" by default, which acts as a safety net. To bypass the Recycle Bin and delete a directory immediately, use the shift+delete keyboard shortcut or the /q option with rmdir:

rmdir /s /q directory
rd /s /q directory

No matter what operating system you‘re using, the principles of deleting directories are similar. Be careful, double check before deleting, and have backups just in case.

Conclusion

Deleting directories in Linux is a powerful tool that every user should know. The rm and rmdir commands are the key players, with rm handling recursive deletion and rmdir as a safer option for empty directories.

Always double check the directory name and path before deleting, and consider using options like -i for confirmation or -v for verbose output. Be extra careful with wildcards and special characters.

If you accidentally delete something important, stop using the system immediately and consult a data recovery expert. The sooner you act, the better your chances of recovery.

With great power comes great responsibility. Use rm and rmdir wisely, and may your filesystem be forever tidy and free of cruft. Happy deleting!

1 Source: 2018 Linux Kernel Development Report, The Linux Foundation

Similar Posts