To delete a file or directory in Linux from the command line, use the command
Be especially careful when deleting files or directories using the command
rmbecause once the file is deleted, it cannot be restored.
In this article, we will show you how to use the rm command to delete files and directories in Linux with examples and explanations of the most common rm options.
How to delete files
- To delete a single file, use the command
rmfollowed by the filename:
If the file is write-protected, you will be prompted to confirm it as shown below. To delete the file enter
Enter… Otherwise, if the file is not write-protected, it will be deleted without prompting.
rm: remove write-protected regular empty file 'filename'?
- To delete multiple files at once, use the command
rmfollowed by the filenames, separated by a space.
rm filename1 filename2 filename3
You can also use the wildcard (
*) and regular expressions to match multiple files. For example, to delete all files with the extension
When do you use
rmwith wildcards (
*) and regular extensions, it is recommended to list the files using the command
lsso you can see what files are going to be removed before running the command
- Use the option
-ito confirm each file before deleting:
rm -i filename(s)
- To delete files without prompting, even if the files are write-protected, use the parameter
rm -f filename(s)
- You can also combine options
rm… For example, to delete all files
.txtin the current directory without prompting in verbose mode, use the following command:
rm -fv *.txt
How to delete directories (folders)
- To remove empty directory use this option
rm -d dirname
- To remove non-empty directories and all files within them, use the option
rm -r dirname
If a directory or file in the directory is write-protected, you will be prompted to confirm the deletion.
- To remove non-empty directories and all files without prompting, use
r(recursive) and parameter
rm -rf dirname
- To remove multiple directories at once, use the command
rmfollowed by the directory names, separated by spaces.
rm -r dirname1 dirname2 dirname3
Same as in files, you can also use the wildcard (
*) and regular expressions to match multiple directories.
By now, you should have a good understanding of how to use the command
rm on Linux and you should learn how to safely delete files and directories using the command line.
Please disable your ad blocker or whitelist this site!