Introduction

How do I delete or remove a file in Linux using command line option? How can I delete a directory?

Deleting files and directories is a necessary and inevitable task when working Linux. In this guide, you will learn how to remove files and directories from the command line in Linux using the RM Command.

Introductory image to removing Files and Directoried using the command line

Prerequisites

  • A command line / terminal window (Ctrl-Alt-T or Ctrl-Alt-F2)
  • A user account with sudo privileges (optional)

How To Remove Linux Files With rm Command

To delete a single file, entering the following in the command line:

rm filename

The rm command can be used  to delete more than one file at a time:

rm filename_1 filename_2 filename_3

Wildcards can be used with this command.

For example, to delete all files with the .bmp filename, enter:

rm *.bmp

This method is also used to delete all files that contain a string of characters:

rm *sample*.*

This will erase any file that has the word sample in the name.

The system will search the current directory for the file you want to delete.

To delete a file in a different directory, either switch to that directory first:

cd /tmp
rm filename

Or you can specify the file location in a single command directly:

rm /tmp/filename

Options with the rm Delete Command

You can adjust the way the rm command works by adding options. An option is a hyphen, followed by one or more letters that stand for commands.

If you’re deleting multiple files add a confirmation prompt. Use the –ioption to use an interactive dialog:

rm –i *.log

To display the progress of the deletion with the v or verbose command:

rm –v *.log

To force the deletion of a file that’s write-protected, use the the –f option:

rm –f filename

To use sudo privileges for file that says Access denied anddelete it:

sudo rm filename

How to Remove a Linux Directory or Folder

To use the rm command to remove a directory, the directory needs to be empty.

  • To specify a directory (instead of a file) use the –d option:
rm –d directory
  • To delete the directory and its contents use the –r option:
rm –r directory

This will prompt you for confirmation before deleting.

  • To force deletion of a directory without requiring confirmation:
rm –rf directory
  • To delete more than one directory or folder at a time:
rm –r directory_1 directory_2 directory_3

Conclusion

With this tutorial, deleting files and directories in Linux was made easy. The rm command is flexible with many options available.