How to Delete Files and Directories in Linux

There’s no secret that we from time to time we delete files and/or directories we don’t need through the GUI, whether its on Linux, MacOS, or even Windows, we have all been there. This guide will teach you how to delete files and directories in Linux through the command line, or terminal with the help of the rm command.

Delete Files and Directories in Linux with rm

The rm command allows us to easily delete files, although by default it does not delete directories or folders, we can still use it to do so with the help of the -r (recursive) flag.

The syntax of the rm command is:

rm flags files or directories

The most commonly used flags are:

  • -r – Recursive mode, allows us to remove directories and its conents.
  • -i – Prompts confirmation of each individual file deletion.
  • -I – Prompts confirmation only once.
  • -v – Verbose mode. Displays what its doing.

Files

Single File

Now that we know a few of the most used flags, and the rm command syntax. To delete any file:

rm flag(s) file_name
example

rm -rv photo.jpg

output

linuxify@app:~# rm -rv photo.jpg
removed 'photo.jpg'
linuxify@app:~#

Multiple Files

Thankfully the rm command allows us to remove or delete multiple files at a time, to do so, simply specify each file name right after each other:

rm flag(s) file_name1 file_name2 . . .
example

rm -rv photo.jpg document.pdf

Pattern or file extension

To remove or delete files based on a pattern or file extension you can use an * (asterisk). In the following example, we’ll remove all files ending with the .txt extension:

rm -r *.txt
Output

linuxify@app:~/demo# ls
test1.txt  test2.txt  test3.txt  test4.txt  test5.txt  test.txt
linuxify@app:~/demo# rm -r *.txt
linuxify@app:~/demo# ls

Alternatively, we can remove files based on their name, for instance (based on the example above):

rm -r test*

Directories

Single directory

Similarly to files, to delete directories in Linux we use the same syntax. In this case we must use the -r flag to do so. Do note that with the -r flag you will remove/delete all the files or contents of the directory.

rm -r directory

Multiple directories

To delete multiple directories, you can specify all of them right next to each other:

rm -r directory1 directory2

Pattern

Alternatively, you can remove directories based on patterns with the use of an * (asterisk).

rm -r directory*
example

linuxify@app:~/demo# ls
directory-1  directory-2  directory-3
linuxify@app:~/demo# rm -ri directory-*
rm: remove directory 'directory-1'? Y
rm: remove directory 'directory-2'? Y
rm: remove directory 'directory-3'? Y
linuxify@app:~/demo#

Summary

This guide focused on teaching you on how you can delete files and directories in Linux with the use of the rm command.

Leave a Comment