How to delete directory in linux
How to delete directory in linux
Remove a Directory in Linux – How to Delete Directories and Contents From the Command Line
Linux is a popular open source operating system, and its features are often available in your development environment. If you can learn its basic commands, it’ll make your life as a developer much easier.
In this guide you will learn how to delete directories and files from the Linux command line.
The Linux rm Command
The rm (short for remove) command is pretty useful. Let’s learn its syntax and look at a few examples to see it in action.
rm Command Syntax
The syntax is shown below, with args being any number of arguments (folders or files).
Without options you can use it to delete files. But to delete directories you need to use the options for this command.
The options are as follows:
Linux rm Command Example
Let’s take a project_folder directory as an example. It has these files and folders inside:
Let’s use this directory to show how the various options work.
It has deleted the project_folder directory and everything inside it, in the order shown.
Let’s recreate the folder and try again.
And you need to press y or n and then Enter after each query.
If you select y for all queries it will delete everything:
If instead you decide to not delete some files or folders, with n it will keep those files and continue with the rest:
Conclusion
Enjoy this new tool in your arsenal!
Moderator and staff author for freeCodeCamp.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Как удалить каталог Linux
Однако в терминале это делается немного быстрее и вы получаете полный контроль над ситуацией. Например, можете выбрать только пустые папки или удалить несколько папок с одним названием. В этой статье мы рассмотрим как удалить каталог Linux через терминал.
Как удалить каталог Linux
Такая команда уже позволяет удалить непустой каталог Linux. Но, можно по-другому, например, если вы хотите вывести информацию о файлах, которые удаляются:
Читайте подробнее про пути в файловой системе в статье путь к файлу Linux. Теперь вы знаете как удалить непустой каталог в консоли linux, далее усложним задачу, будем удалять папки, которые содержат определенные слова в своем имени:
Как видите, в find необязательно выполнять отдельную команду, утилита тоже умеет удалять. Вместо домашней папки, можно указать любой нужный вам путь:
Перед удалением вы можете подсчитать количество пустых папок:
Если вы хотите полностью удалить папку Linux, так, чтобы ее невозможно было восстановить, то можно использовать утилиту wipe. Она не поставляется по умолчанию, но вы можете ее достаточно просто установить:
sudo apt install wipe
Теперь для удаления каталога Linux используйте такую команду:
Выводы
В этой статье мы рассмотрели как удалить каталог linux, а также как удалить все файлы в папке linux без возможности их будущего восстановления. Как видите, это очень просто, достаточно набрать несколько команд в терминале. Если у вас остались вопросы, спрашивайте в комментариях!
How to Remove a Directory in Linux
Home » SysAdmin » How to Remove a Directory in Linux
Removing a directory in Linux is a pretty simple task if you are using the GUI. However, if you don’t have access to the GUI, you can also remove directories using terminal commands.
In this tutorial, we will show you how to remove a directory in Linux via commands in the terminal window or command line.
Note: For other Linux directory management articles, see How to Move Directories in Linux and How to Rename a Directory in Linux.
How to Remove a Directory in Linux?
There are two Linux commands you can use to remove a directory from the terminal window or command line:
It is important to note that the rm and rmdir commands permanently remove directories without moving them to the Trash directory. This means that you cannot restore a directory removed using these commands.
Note: Even though rm and rmdir permanently remove files and directories, users with enough skill and time still have a chance of restoring some of the removed files. If you want to learn more about removing files permanently, have a look at our shred command tutorial.
rm Command
The rm command in Linux removes files and directories.
It uses the following syntax:
Note: To remove multiple files or directories using the rm command, add multiple file or directory names, separated by blank spaces.
The different rm command options include:
Trying to use the rm command without any options to remove a directory results in an error message:
If you want to remove an empty directory, add the -d flag to the rm command:
The example below shows that the rm command with the — d flag removes the Example directory:
Use the -r flag to delete a directory that contains subdirectories and files.
The image below shows the tree hierarchy of the Example directory, which contains Dir1 and Dir2 subdirectories, with multiple text files in each:
Using the -r flag removes the entire directory, including subdirectories and files, while the -v flag lists each step of the process as the output:
The -i option displays a prompt asking you to confirm directory removal. Type Y and press Enter to confirm.
rmdir Command
The Linux rmdir command removes empty directories only. The command uses the following syntax:
The rmdir command includes the following options:
Using the rmdir command on a non-empty directory produces an error:
In this case, the Example directory contains the Test subdirectory:
To remove these directories using the rmdir command, add them in reverse order of hierarchy. Using the -v option lists each step of the process as the output:
A simpler method of doing this is to use the -p option with the subdirectory’s name. This removes both the subdirectory and its hierarchical parent:
The rmdir command allows you to remove multiple directories with similar names using wildcards. For instance, if you want to remove directories named Example1, Example2, and Example3:
After reading this tutorial, you should be able to remove directories in Linux using commands in the terminal window or command line.
To learn more about other commands in Linux, check out our Linux commands cheat sheet.
How to Delete a Directory in Linux
Deleting files and directories in Linux is as easy as ABC.
There are a couple of ways to go about deleting a directory in Linux. You can either handle it graphically from your desktop environment or do it directly from the command line. Either way will work, and they’re both just as effective.
Graphical Method to Delete a Directory in Linux
Every desktop environment (and file manager) is slightly different. This article will walk through the steps of using Budgie with Nemo as a manager, but the process is roughly the same with every desktop.
Open your file manager and browse to the location of the directory you want to delete. Once you’ve found it, right click on that directory to open the menu of available actions. Depending on your environment, you may see both “Delete” and “Move to Trash” or just “Move to Trash.” It’s always a safer bet to move the directory to the trash, as you can recover it if you make a mistake. Click “Move to Trash” on your menu.
The file manager will sometimes ask you if you really want to delete the folder. Confirm that you do. The directory will move from its current location and will appear in the trash folder instead. There’s only one step left to completely zap it from existence!
If you’re absolutely sure you don’t need the directory you just removed, open the trash. You’ll see the folder there, and you can even browse its contents.
If there’s nothing there that you need, you can either right click on the folder itself to delete it permanently or click in the white space of the directory to bring up a menu with the option to empty the trash. In Nemo, there’s a convenient “Empty Trash” button (depicted) near the top-right corner of the window. Do whichever you prefer. Remember, there’s no way to undo this. The directory isn’t coming back.
Using the Command Line to Delete a Directory in Linux
There’s an even more direct way to remove a directory from the command line. The rm command can be used to remove both files and directories.
This is useful as a method that will give you more control over the file removal system or as a means to delete something when your file manager is inaccessible.
To fully explain what this command can do, we need to open a terminal and navigate somewhere safe to test various commands. The Documents directory inside your home folder should do just fine.
is a symbol that represents your home directory.
That didn’t quite work, did it?
Although rm ‘s manual describes the command’s function as “remove files or directories,” there’s a little caveat: the command by itself will not remove directories.
Try this again, but this time, put a few files into Test. You can do this easily with your file manager, but since you’re already in the terminal, why not have a little fun doing it with a few other commands that may be useful at a later time?
There’s More to It than Meets the Eye
-i – Prompts you for each file deletion. It’s useful when doing a recursive removal of a folder containing files you may or may not remember being important. When you want to confirm the deletion, type y when prompted. Type n if you want to keep that file. Keeping a file during a recursive removal may stop the removal process. Example:
-d – Removes a directory only if it’s empty. This is an essential flag when you want to clear up folders that you never bothered to fill. It comes especially handy when you want to write a script that deletes all empty folders in a particular area of your drive. If you’re just issuing commands in the terminal, you won’t find much use for this flag. Example:
-v – Runs rm in verbose mode. This flag helps you troubleshoot issues by looking at what rm tells you each step of the way while trying to execute your instructions. If something is not quite right, this is what you use to walk through the process. Example:
—version – Tells you which version of rm you’re running. You’ll probably never need to use this flag, but it’s there in case you’re wondering if you’re on the latest version.
Just One More Command
Frequently Asked Questions
1. What do I do if I get “permission denied”?
If you are having trouble with permissions when deleting something, first double-check that you’re not trying to delete something essential to your system or applications you use. Once you’re sure you’re just deleting some unessential file or directory, go to your terminal and type sudo before your rm command. This should bypass any permission restrictions.
Don’t feel like using the command line? Most file managers installed with Linux distros should be able to help you here. Right-click any empty space in the file view, and you should see an option saying “Open as root” or “Open as Administrator”. Click on that, and enter your password when prompted, a new window should open with elevated privileges, allowing you to do whatever you want to your heart’s content.
2. Is rm safe?
Yes and no. The rm command is only a deletion command. It doesn’t question whether the files and directories you are deleting is sensitive or not. As long as you’re certain you’re not deleting something that shouldn’t be deleted, rm is safe.
Generally, you won’t cause problems to the operating system if you stick within the bounds of the “/home” directory. Once you venture beyond that, you are no longer in calm seas and should really watch where you sail.
3. Can I use rm or rmdir in other operating systems?
This depends entirely on which operating system we’re talking about. The rm command for macOS is strikingly similar to Linux’s, which isn’t surprising considering that both wear the old gown that once was UNIX.
Conclusion
With all the information provided here, you will hopefully come out of reading this with a level of confidence in using your terminal and file manager to clear your drive of clutter. Just don’t forget to tread carefully and take each step with some level of respect for the power you wield. There’s no need to hurry. Your terminal and file manager aren’t going anywhere!
Our latest tutorials delivered straight to your inbox
How to Remove or Delete a Directory in Linux
Linux is the best-known open-source operating system that is popular among programmers and computer professionals. Often new developers come across instances on Linux, where they are not sure on which command to use. For example, one of the most common queries among amateur developers is to know how to delete or remove the directory in Linux.
Not all programmers become experts overnight, and therefore we are here to help them in a step by step guide to delete a directory in Linux. We will be covering all the methods that programmers can use and choose the one that they find convenient.
Before we start, let us understand why Linux is so important and the reason there are more and more new Linux programmers. First and foremost, Linux is open-source, so there is always someone to help, and a programmer can never fill isolated. There are tons of resources online that can help anyone learn and master Linux. While a very common preconception that Linux is only for the developer is very untrue, as Linux is more common than many might believe.
It is the underpinning operating system of every Android phone. Android-based phones make up for more than seventy per cent of the total mobile market share. More so, almost every website is powered by Linux-based servers. Therefore, it makes it one of the most widely used operating systems in the world.
However, coming back to removing a directory on Linux. You have come to the right place if you are looking for ways to delete a directory either graphically or using the command line. Programmers must remember that everything is considered a file on Linux, even a directory. In other words, a directory is nothing but a group up files placed together. For those switching from Windows operating system or macOS, a directory is the same as a folder in Windows.
Ways to Delete a Directory on Linux
Linux is a simple and very straightforward operating system and offers a couple of ways to delete a directory in Linux. The first method is by removing it graphically from the desktop environment. For those who are using Gnome’s File can delete a directory using the graphical user interface.
Another way is to use the command line, which is more effective. The latter is common when a system is using a headless server. The command-line option is even more effective when a coder has to remove multiple directories at the same time.
Cautionary Points
Delete a Linux Directory Using GUI
On Linux, graphically removing a directory is easy and straightforward akin to Windows or macOS system. More so, one must also remember that all desktop environments are not the same. On the flip side, they do not differ significantly, and it is straightforward to understand any Linux distribution.
For example, we will use the KDE Plasma is a graphical workspace environment. The KDE Plasma is developed by an international software community known as KDE. Their main objective is to create free and open-source software that can help the Linux community. It also develops cross-platform application such as Krita that can work on Unix, Android and even Microsoft Windows.
Let us look at the steps to remove a directory on Linux using the KDE Plasma GUI.
Programmers must remember that there is no coming back from it and one can not recover it ever.
Delete a Linux Directory Using Command Line
Akin, to major operating systems, even the Linux offers a couple of ways to permanently remove a folder using the command line. The two Linux commands to delete directories are rmdir and rm.
The above commands are similar to del and deltree on Windows operating system. The rmdir and rm are known as one of the most powerful commands on Linux. More so, one must also take caution that unlike the GUI option, deleting files using the command line does not move the folder to the trash. The directory is permanently deleted from the system. However, if a programmer accidentally removed a file using the command line, then they can only recover it from a backup.
Below we will explain both of the above commands in detail with examples.
Removing Directories With rmdir
The rmdir is a command-line utility that programmers use to delete directories on a Linux machine. The command is often used to remove empty folders. Therefore, it is convenient for those who want to delete a directory or directories that are empty as they do not have to worry whether they are empty or not. If the files in them, then the command, will return with an error message.
But first, let us look at the syntax of the commands.
As aforementioned that the rmdir deletes directories if they do not contain any sub-directories and are empty. Here is the syntax for the same:
rmdir [option] directory-name
For example, to remove the abcd1, open the terminal and enter the following expression:
An error message will return, such as the following:
rmdir: failed to remove ‘abcd1’: No such file or directory
If this is the case, then one has to manually move the content of the directory or use the rm command-line utility.
It is one of the significant differences between the rmdir and rm commands. Therefore, using the rmdir command is very beneficial as programmers never have to worry about deleting when executing it as it never removes a file. Also, one can use multiple directories and even write the path of the folder.
For example, to delete multiple directories, all a coder has to do is enter the following expression:
rmdir abcd1 abcd2 abcd3
Also, for those who want to delete a folder that is not the current directory, then one can enter the full path of that particular directory that is to be deleted. Here is an example of the same:
If the directory is empty, then the command-line utility deletes it silently and successfully. Now, for instance, you have multiple directories in a path and wish to delete the empty ones, what do you do? It is simple you just run the rmdir command, and it will only delete the empty ones. The rmdir does not even make any changes to the files with a directory that has content. It is left untouched.
But the rmdir works in a sequential manner. So, if you execute a command to delete five directories and the first one returns with the error message “Directory not empty”, then the whole process is terminated. However, one can use the following command : —ignore-fail-on-non-empty, to force the process to continue and ignore the directory that files. So, for example, if the folder work/abcd1 has content, then one has to execute the following command:
The result is that the above command deletes both «work» and «abcd» folders.
Removing Directories With rm
The rm is another command-line utility that allows coders to delete directories. Beyond that, rm can also remove files and not only directories. Therefore, it is a must that programmers take caution before using it.
It is one way the rm is different from rmdir as it removes not only empty directories but also the ones that are filled with content if one is sure that it is a great way to delete non-empty directories.
The command will return for confirmation of the deletion, type “Y” and press Enter.
The expression will remove all files recursively without prompting for permission to delete each file in the folder. The rm is very useful and is often regarded as one of the most popular commands on Linux.
Now, what if a user wants to delete specific files that have something in common? Once again, the rm comes to rescue and can easily remove particular files using regular expressions. For instance, to delete all the that ends with _xyz in the current directory, a coder has to type the following:
However, the programmer must be cautious when using regular expression with rm as it is risky. The best way is to first list all the directories by using the ls command. Using ls, one can view all the directories before being removed.
To remove multiple empty directories at the same time, type the following:
As one must have noticed that there are multiple ways to delete a directory and one can use any of them. While a programmer can use the rmdir to remove empty folders, the same can be possible with the rm command.
One can always use the tree command to understand better what files will be removed before executing the rm expression. First, a user has to install a package before using the command. For Ubuntu users, one can leverage the apt-get command to install packages. For other Linux distributions, programmers can leverage the package management tool of that particular distribution. So the expression would look something like this:
sudo apt-get install tree
The tree command gives users a simple understanding in a diagram formation of the directory structure and the contents such as files beneath the directory.
Interestingly, a programmer can even specify a path to tree command, so it begins with another directory from the files system.
Removing Files With rm
While we have learnt to remove a directory with rm, it is best to also know on how to delete a single file using the rm command. It is essential to learn it as it comes handy, especially when a coder wants to remove a single file from a current directory.
In case, the file is placed in another directory; then one has to provide the path and the file name. Below is the example for the same.
The rm command is convenient as a programmer can even delete multiple files. Check out the below example:
rm work_1.txt work_2.txt work_3.txt
Now, type the following expression to remove all files with a single character extension:
Removing Directories With find
While the two most common command-line utilities to delete a directory are rm and rmdir, there is one other option as well. To one’s surprise, a programmer can even leverage the find command to delete a directory. It is a command-line utility that permits programmers to search for files and directories and then perform a specified action on the files and folders that match the expression.
One another important use of the find command is to remove directories. For example, if one wants to delete all folders that end with _tmp in the current directory, then type the following command:
Let’s breakdown the expression.
Now, what if one wants to remove all empty directories in a directory tree? Deleting an empty directory is very easy and let’s check the below example:
Common Errors Using rm, rmdir and find
Each of the command-line utilities is very beneficial and eases the work of removing files. But it is not always smooth sailing as at times one can come across error messages. As aforementioned, the most common error message when using the rmdir command is one witness is “Directory not empty.” Programmers can always bypass it by using the —ignore-fail-on-non-empty command. However, there are multiple other errors that one can face when executing the command.
For example, one can get the error /bin/rm: Argument list too long when executing the find and rm command. The error is common when the rm command attempts to delete a folder with a huge number of files. It happens because the size of the data is more than the size limit of the command line argument.
However, coders don’t have to worry as there are multiple solutions to overcome the issue. Programmers can use cd to the directory or even use the loop to delete subdirectories sequentially. The best solution for the error is to remove all files in the current directory with the find command and then try and delete the folder. Here is the expression for the same:
The above is a detailed brief on ways to delete or remove a directory from Linux. Linux offers flexible and powerful commands to perform any task. Some Linux users prefer GUI interface while others use a headless system such as the Raspberry Pi that entirely functions on command-line.
An additional perk of using Linux is that it does not matter whether you use Bash or any other shell; it is easy and convenient to perform most tasks. Coders can quickly delete directories from the terminal command.