Share via:

RM: Delete Files and Directories in Linux

How to use the rm command to delete files and directories in Linux.

974 views

Edited: 2019-12-11 12:20

Linux tutorial

The rm command can be used to delete files and directories in Linux.

To delete a file or folder, one would simply use rm in the following manner:

rm PATH-TO-FILE-OR-DIRECTORY

Depending on permissions, you may need to write sudo in front of rm.

sudo rm /var/www/mysite/index.html

You can also navigate to the directory before deleting the file using the cd command.

cd /var/www/mysite
sudo rm /var/www/mysite/index.html

To move back to your home directory, do something like this:

cd /home/MyUser

Deleting a directory and all its contents

A common problem on Linux is how to delete a directory, including all its contents, since the "rm" command does not work as many intuitively expect.

To recursively delete an entire directory, including the content, we can use the following:

rm -r directory

To avoid getting prompted for every file, we can use the -f flag:

rm -rf directory

The command is useful when writing scripts and managing a computer or server remotely. Mostly since you typically do not have access to a GUI in those cases. It is mostly personal preference, but some users find it faster to use the terminal, while others find it difficult to remember commands.

Using the terminal vs your file manager

Alternatively you may also delete files and folders with your favorite file manager. Nemo makes it easy, as it has the option to "Open as Root" when right clicking on a directory. But you could also launch Nautilus as root.

Many Linux users prefer to use the terminal, and resist using GUIs. However, any modern OS should be expected to offer GUIs, both for productivity, and to make things easier for their users. When using the terminal, users often have to learn and memorize complex commands – something we can not expect users to do.

Nautilus may be launched with the following command:

sudo -i nautilus

See also: The Problem with Sudo and Graphical Applications

Rm Options

OptionWhat is this?
-v or --verboseShow what is being done. I.e. Prints the filename, before removing the file.
-f or --forceIgnore nonexistent files and doesn't prompt the user.
-iPrompt the user before removing each file.
-IPrompt once whether to proceed with the command, if more than three files are named or if a recursive removal is requested.
--interactive=oncePrompt once whether to proceed with the command, if more than three files are named or if a recursive removal is requested.
--interactive=neverShow no Prompts to the user at all.
--interactive=alwaysPrompt for every file being removed.
--interactiveEquivalent to --interactive=always

Comments