How to Remove All Files from a Directory in Linux

In this tutorial, we are going to learn how to use rm command to remove all files safely from a directory. This document helps you delete non-hidden files, files with specific extensions, hidden files inside a directory.

01. To delete all non-hidden files from a directory, type:

$ rm -f /path/to/directory/*

02. To remove all the file with the extension .txt from a directory, type:

$ rm -f /path/to/directory/*.txt

03. To delete all non-hidden files and sub-directories along with all of their contents from a directory, run:

$ rm -rf /path/to/directory/*

04. To delete all hidden files and directories from a folder, type:

$ rm -rf /path/to/directory/{*,.*}

05. To delete all the files from inside a folder but not removing its sub-directories:

$ rm -f /path/to/directory/{*,.*}

06. To remove a folder whose name has space, make sure to always use quotes like:

$ rm -rf "directory name”

You can also use backslack to remove spaces by escaping the space.

For example:

To remove the directory named 'Good Morning', type:

$ rm -rf Good\ Morning

07. You can see what is being done when deleting all files in directory pass the -v option to the rm command:

$ rm -v /path/to/directory/*

08. To remove all the file from a directory having extension .sh you can use find command too,

$ find . -type f -name "*.sh" -exec rm -i {} \;

Note: In place of "*.sh" just give "*" to delete all the files.

Understanding rm command option

rm : Remove (unlink) the FILE(s).
-f : ignore nonexistent files and arguments, never prompt
-r : remove directories and their contents recursively
-v: see what is happening

Conclusion

You need to be careful while removing the file on the Linux system. Using the command 'rm' will not store files in the trash. On the other hand, be careful while using wildcard like '*'.

Leave a Comment