Linux users frequently create lots of files, folders, and directories. Directories may further contain nested sub-directories and files within them.
At some point in time, like we do with the windows, you may need to delete the created file. That’s easy. Here’s the syntax to delete a file created in Linux:
For example: $ rm xyz.txt
This command will remove the text file in your system with name “xyz”.
Deleting a Non-Empty Directory in Linux
But deleting a directory can be tricky. The Linux command used for deleting a directory is:
Here DIRNAME takes the names of the directory that you want to delete. But you have to extremely careful while using this command. For using this command to delete a directory, users have to empty the directory of files and folders before removing it. But it can be a time-consuming and frustrating job if your directory has multiple levels. Deleting many numbers of files and folders can be tiresome.
When users try to remove a director using the rmdir command, the following error message prompts on the screen: “Directory not empty.”
Making the things easier, Linux offer a shortcut command to delete a non-empty directory from the Linux terminal as the command runs. The syntax for removing a full directory is:
rm –r mydir
Here, r stands for recursive and you would replace mydir with the name of your directory. For example, if your directory name is Mydata and you type the following on Linux terminal:
rm –rf Mydata
As soon as you hit this command, it would delete all files and nested directories created within the directory named Mydata.
If the rmdir command makes the thing so easier, it also comes with associated risks. In case you unintentionally run this command, you would lose all the files. However, as you execute this command, a prompt for your approval will be opened on your screen.
If you are sure that you want to delete a non-empty directory from the Linux terminal and don’t want approval prompt to appear on your screen, you can directly run the following command instead:
rm -rf mydir
Here f represents the forced removal of an entire directory without any prompt messages. With this command, the entire directory will be deleted with its files and folders without any prompt message.
Besides using the rm command, users can also use rmdir options in the given order: –ignore-fail-on-non-empty: Ignore the command failure that occurs only because the directory was non-empty. -p: Use this option to delete nested directories. -v, –verbose: Display information for every processed directory. –help: Display a help message and exit. –version: Give version information and exit.