In Linux, we can either delete/remove a single file or delete all the files from a directory using a single command in a terminal. In this write-up, we will discuss the ways to remove all the files in a directory of Linux.
How to remove all files in a directory of Linux
We have directories in a path /home/hammad/ with a name, new_directory, new_directory1, new_directory2, and new_directory3 that contain files, to view it, and list down the components of the path:
To view the files of “new_directory”, use the command:
To remove these files from the directory “new_directory”, we can simply use the command of “rm”, the general syntax of using the rm command is:
The explanation to the syntax is simple:
- Use the command of rm to remove the files from the directory
- Use any options like to display the progress, to remove it forcibly
- Type the pathname where the directory is located
- Mention the filenames which you want to remove or simply use “*” to remove all the files from the directory
Suppose we want to remove all the files from the “/home/hammad/new_directory/*” path, we will use the command:
We can also display the progress of the removed files by using the flag “-v”, we will execute the command:
In the above command, the “-v” flag is used to display the progress of the command where “*” is used to delete all the files of the directory and for verification that all the files are deleted, we will again list down the content of the directory using the command:
The above command verified that the directory contains no files and there are some other useful options as well; the “-f” which is used to delete the files forcibly and “-r” deletes the directory and its files, we will use all these flags altogether to delete the files of “new_directory2”
In the above output, we can see that the “-r” flag removes the sub directory, “officedirectory”, from the new_directory2, to list the files of new_directory2, we use the ls command:
We have another option that is “-i”, if we use this option, it will ask for permission before deleting each file should we continue to delete it or not, if we still want to delete it, type “y” or “n” to cancel it. We will use “-i”, to delete files of new_directory3:
In the above command, it can be seen that we have confirmed to delete “myfile” and canceled to delete “myscript.sh”, to view the files in the folder:
We can see the “myscript.sh” file has not been removed from the directory.
To delete all the empty directories we use the “rmdir” command:
All the empty directories are removed, use ls command to verify:
Removing the files from the directory will create free space for the new files and applications. Therefore, files of no use should be removed from the system. To remove all the files from the directory the convenient way is to use the rm command which is discussed in this write-up. Different options can also be used along with the rm command which is also discussed with the help of examples.