In this section, we will look at more on how to remove a file or directory on the Linux/UNIX flavor machines.
Let’s start with rmdir command.
This is used for removing of an empty directory. An empty directory means, having no files and subdirectories in it.
rmdir command execution,
In practical, we don’t use this rmdir command so frequently. Main reason is,
Most of the times, every directory will be having at least few files and subdirectories under it. So to use this command, we have to manually eliminate each and every file and subdirectory of it. which is a tedious task.
The best solution is using “rm command” with “-rf” option.
rm command is primarily used to remove single or multiple files under a directory.
Let’s understand some of its practical usages with examples.
Removing a particular file:
Removing a file is a straightforward requirement and there are so many of the cases for this.
Some practical usage cases,
We have worked on a sample file and want to delete after its usage.
We might find a corrupted configuration file and want to remove it and copy a new file from backup.
sample rm command output is given below,
The one problem is, it will be removing the file without even prompting and once the file is deleted in Linux/UNIX flavor OS, we can’t pull it back.
So always best practice is to prompt for deletion of a file.
rm command with “-i” option, will prompt the user whether to delete a file or not.
Force removing a file:
We can remove the file using "-f" command with rm command it won't prompt for confirmation to delete it or not.
Observe the following case for the proper understanding.
Removing multiple files at a time:
For removing multiple files, we will use rm command followed by file names
Observe the following usage for more understanding.
If we want to delete all files under a particular directory using rm command, we can use directory name followed by a star as indicated below.
Practical usage case,
We might want to remove files from /tmp directory for memory free.
Removing a directory with files and subdirectories under it:
We can remove the directory including directories and files in the particular directory using rm command with "-r" option in this r indicates recursive.
Practical usage case,
Suppose a package is uninstalled/ removed from the system but the files and directories used by that package will be there and consume some amount of storage. to free that storage we will remove that
directory with "rm -rf' command
Removing the files having the same extension:
In some cases, we need to remove all files having the same extension. we use wild cards in these scenarios.
to understand more follow the following scenario.
Possible issues we might face while removing a file or directory: