Linux is hard for many people, I used to feel the same way. But trust me Linux is not hard, we don’t use it regularly so it seems hard to us. Today I’ll try to explain how to remove files and folders (directories) in the Linux operation system using the command line. This tutorial mostly ill will try to explain the “rm” command and its detailed use. I personally use CentOS but the commands should work fine for other OS too.
How to Remove Files
You can use eitherrm
or unlink
both commands to delete (remove) a file. The unlink
command can only delete a single file, to delete multiple files you have to use the rm
command. Always careful before using these commands because once you remove a file it is not easy to bring the file back. Recovery options are always complicated.
You need to be in the same directory as the file and use the command.
unlink filename
rm filename
If you want to delete a file that is write-protected, after using any of those commands, you will be prompted for confirmation, as shown below.
rm: remove write-protected regular empty file 'filename'?
You have to type y
and press enter
to delete the write-protected file.
You can also delete multiple files with the rm
command. You need to specify the file names separated by space after the rm
command.
rm filename1 filename2 filename3
If you want to delete all files with the same type, you can use (*
) to match multiple files. For example, if you want to delete all your .mp4 files you can use the command below
rm *.mp4
Use the command below to force delete a file. simply add -f
the (force) option to the rm
command.
rm -f filename
How to Remove Folders (Directories)
To delete a directory, you can use bothrmdir
and rm
commands. With the command, rmdir
you can only remove an empty directory but with the rm
command, you can remove the folder and files in it.
Let’s see the basic use of rmdir
and rm
commands. Both commands below are used to delete empty directories.
rm -d dirname
rmdir dirname
If you want to delete a folder with files in it, you need to add -r
a (recursive) option with the command rm
rm -r dirname
If the files are write-protected, you will be asked to confirm the deletion for each file. This could be annoying. you can simply add -f
the (force) option to avoid the confirmation.
So to remove a non-empty folder including all files in it and without being asked for confirmation, you need to use the command below.
rm -rf dirname
To remove non-empty multiple folders you can use the command below.
rm -r dirname1 dirname2 dirname3
or
rm -rf dirname1 dirname2 dirname3
Conclusion
Yep, This is it. By now you should have a good understanding of removing (deleting) files and folders in the Linux operating system. The topic discussedrm
, rmdir
and unlink
commands and the use of them. Always be cautious before deleting any files or folders because once you delete it, it's gone for good.