Share via:

How to Recursively Delete a Directory

How to delete a directory and all of its contents in Linux, including subdirectories and files.

52 views

Edited: 2019-08-24 21:34

When handling files and directories in Linux, a common problem one might run into is with deleting directories that are not empty.

Most users probably rarely use the terminal, and even those of us who do might still not remember how to use the commands. Remembering parameters is simply more difficult to me than remembering the command itself, and I have often wondered why not just have a "smart" command that automatically does what we expect.

We can not use rmdir, since that will result in a error like:

rmdir: failed to remove 'dirName/': Directory not empty

The simple answer as to why this is the default behaviour, presumably, is to avoid mistakes where a user might accidentally delete an entire directory and its contents.

The solution is instead to use the RM command with the recursive -r flag:

rm -r directory

To also avoid getting prompted about each and every file we should also include the -f flag:

rm -rf directory

If you find this behaviour annoying, you can add your own delete script to your ~/local/bin folder. Typically you would just create a simple wrapper shell script rather than your own compiled replacement.

#!/bin/bash
# Example of a simple wrapper script to delete a file- and/or directory (including contents) without asking,
# The purpose is to avoid the need to remember typing rm -rf as "delete" is more intuitive to users
# Usage: start typing "del" in a terminal, and then hit tab to autocomplete. I.e.: deleteit /path/to/directory
rm -rf $1

Using a GUI File Handler

Some tasks might be easier accomplished from a GUI – even for advanced users. To some users, this even includes simple tasks such as deleting files and folders, and I do not blame them. The rm -rf method is far from intuitive to remember!

However, we may also use a file manager, such as Nemo, to delete the directory. With Nemo, you can even open a directory as root, allowing you to delete just about any file on the system.

Nautilus can also be opened as root, but it does not have a "open as root" option in the right-click menu, unlike nemo does. Before you do this, you should read this article:

Comments