- How to Delete a File or Directory in Linux – Command to Remove a Folder and its Contents
- How to Delete a File in Linux
- Using the GUI file manager
- Using the rm command
- Using the shred command
- Using the trash-cli command
- How to Delete a Directory in Linux
- Using the rm command
- Using the rmdir command
- Conclusion
- Как удалить каталог Linux
- Как удалить каталог Linux
- Выводы
- Remove Directory in Linux – How to Delete a Folder from the Command Line
- Syntax of the Linux rm Command
- How to identify a folder to remove
- Examples of Linux rm command
- How to delete a folder that’s not empty
- How to delete an empty folder
- How to use the -f «force» flag
- Wrapping up
How to Delete a File or Directory in Linux – Command to Remove a Folder and its Contents
Shittu Olumide
In Linux, deleting files or directories is a fundamental operation that every user must know. Although it may seem like a straightforward task, there are different methods to delete files or directories, each with its specific use case.
This tutorial will provide a step-by-step guide on how to delete files or directories in Linux. We will also walk through the commands you can use to remove files and folders along with their content.
How to Delete a File in Linux
Deleting a file involves removing the reference to the file from the file system. The file itself is not immediately removed from the storage device, but its space is marked as available for reuse.
There are several ways to delete a file in Linux. Here are some of the most common methods:
Using the GUI file manager
Most Linux distributions come with a GUI file manager that allows you to delete files using a graphical interface. Simply navigate to the file you want to delete, right-click it, and select «Delete» or «Move to Trash.»
Using the rm command
You can also use the rm (remove) command to delete files and directories in Linux. To delete a file using the rm command, type the following command in the terminal:
Make sure you replace filename with the name of the file you want to delete. If the file is write-protected or you don’t have sufficient permissions to delete it, you will be prompted to confirm the deletion.
Using the shred command
The shred command is a more secure way to delete files by overwriting the file’s contents multiple times before deleting it. This makes it difficult for anyone to recover the deleted file.
To use the shred command, type the following command in the terminal:
Make sure to replace filename with the name of the file you want to delete. The -u option tells shred to delete the file after overwriting it.
Using the trash-cli command
The trash-cli command provides a safer way to delete files by moving them to the trash instead of immediately deleting them. To be able to use the trash-cli command, you install it first:
sudo apt-get install trash-cli
After installation, you can delete a file using the following command:
How to Delete a Directory in Linux
To delete a directory in Linux, you can use the rmdir or rm command. You use the rmdir command to remove an empty directory, while the rm command removes a directory and all its contents.
Using the rm command
Here are the steps to delete a directory in Linux using the rm command:
- Open the terminal: To delete a directory in Linux, you need to use the command line. Open the terminal by pressing «Ctrl+Alt+T» on your keyboard or by searching for «terminal» in your system’s application launcher.
- Navigate to the directory you want to delete: Use the cd command to navigate to the directory you want to delete. For example, if the directory you want to delete is called my_directory and is located in your home folder, type cd ~/my_directory and press «Enter».
- Check the contents of the directory: Before deleting the directory, it is a good idea to check its contents to make sure you are deleting the right directory. Use the ls command to list the contents of the directory. For example, type ls and press «Enter» to see the files and folders inside the my_directory folder.
- Delete the directory and its contents: To delete the directory and all its contents, use the rm command with the -r option, which stands for recursive. Type rm -r my_directory and press «Enter». You will be prompted to confirm the deletion. Type y and press «Enter» to confirm.
- Verify that the directory has been deleted: To verify that the directory has been deleted, use the ls command to list the contents of the parent directory. For example, if the my_directory folder was located in your home folder, type ls ~/ and press «Enter». The my_directory folder should no longer be listed.
Note: Be very careful when using the rm -r command, as it can delete files and directories irreversibly.
Using the rmdir command
Here are the steps to delete a directory in Linux using the rmdir command:
- Open the terminal: Open the terminal by pressing «Ctrl+Alt+T» on your keyboard or by searching for «terminal» in your system’s application launcher.
- Navigate to the directory you want to delete: Use the cd command to navigate to the directory you want to delete. For example, if the directory you want to delete is called my_directory and is located in your home folder, type cd ~/my_directory and press «Enter».
- Delete the directory: To delete the directory, use the rmdir command followed by the name of the directory. Type rmdir my_directory and press «Enter». If the directory is not empty, you will receive an error message and the directory will not be deleted.
- Verify that the directory has been deleted: To verify that the directory has been deleted, use the ls command to list the contents of the parent directory. For example, if the my_directory folder was located in your home folder, type ls ~/ and press «Enter». The my_directory folder should no longer be listed.
Conclusion
The rm command is the most commonly used command for deleting files, while the rmdir and rm commands with the -r or -R options are used for deleting directories. By following this step-by-step guide, you can now effectively delete files or directories in Linux.
- Be careful when using the rm command with the -r or -R option as it can delete files and directories irreversibly.
- Always double-check the file or directory name before deleting to avoid accidentally deleting the wrong file or directory.
- Use the shred command only when necessary, as it can take longer to delete files than other methods.
- Be mindful of file permissions when deleting files or directories, as some files or directories may require root access to delete.
Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.
Как удалить каталог Linux
В операционной системе Linux можно выполнить большинство действий через терминал. Удаление каталога Linux — это достаточно простое действие, которое можно выполнить просто открыв файловый менеджер.
Однако в терминале это делается немного быстрее и вы получаете полный контроль над ситуацией. Например, можете выбрать только пустые папки или удалить несколько папок с одним названием. В этой статье мы рассмотрим как удалить каталог Linux через терминал.
Как удалить каталог Linux
Существует несколько команд, которые вы можете использовать для удаления каталога Linux. Рассмотрим их все более подробно. Самый очевидный вариант — это утилита rmdir. Но с помощью нее можно удалять только пустые папки:
Другая команда, которую можно применить — это rm. Она предназначена для удаления файлов Linux, но может использоваться и для папок если ей передать опцию рекурсивного удаления -r:
Такая команда уже позволяет удалить непустой каталог Linux. Но, можно по-другому, например, если вы хотите вывести информацию о файлах, которые удаляются:
Команда -R включает рекурсивное удаление всех подпапок и файлов в них, -f — разрешает удалять файлы без запроса, а -v показывает имена удаляемых файлов. В этих примерах я предполагаю что папка которую нужно удалить находится в текущей рабочей папке, например, домашней. Но это необязательно, вы можете указать полный путь к ней начиная от корня файловой системы:
Читайте подробнее про пути в файловой системе в статье путь к файлу Linux. Теперь вы знаете как удалить непустой каталог в консоли linux, далее усложним задачу, будем удалять папки, которые содержат определенные слова в своем имени:
find . -type d -name «моя_папка» -exec rm -rf <> \;
Подробнее про команду find смотрите в отдельной статье. Если кратко, то -type d указывает, что мы ищем только папки, а параметром -name задаем имя нужных папок. Затем с помощью параметра -exec мы выполняем команду удаления. Таким же образом можно удалить только пустые папки, например, в домашней папке:
find ~/ -empty -type d -delete
Как видите, в find необязательно выполнять отдельную команду, утилита тоже умеет удалять. Вместо домашней папки, можно указать любой нужный вам путь:
find /var/www/public_html/ -empty -type d -delete
Перед удалением вы можете подсчитать количество пустых папок:
find /var/www/public_html/ -empty -type d | wc -l
Другой способ удалить папку linux с помощью find — использовать в дополнение утилиту xargs. Она позволяет подставить аргументы в нужное место. Например:
find ~/ -type f -empty -print0 | xargs -0 -I <> /bin/rm «<>«
Опция -print0 выводит полный путь к найденному файлу в стандартный вывод, а затем мы передаем его команде xargs. Опция -0 указывает, что нужно считать символом завершения строки \0, а -I — что нужно использовать команду из стандартного ввода.
Если вы хотите полностью удалить папку Linux, так, чтобы ее невозможно было восстановить, то можно использовать утилиту wipe. Она не поставляется по умолчанию, но вы можете ее достаточно просто установить:
Теперь для удаления каталога Linux используйте такую команду:
Опция -r указывает, что нужно удалять рекурсивно все под папки, -f — включает автоматическое удаление, без запроса пользователя, а -i показывает прогресс удаления. Так вы можете удалить все файлы в папке linux без возможности их восстановления поскольку все место на диске где они были будет несколько раз затерто.
Выводы
В этой статье мы рассмотрели как удалить каталог linux, а также как удалить все файлы в папке linux без возможности их будущего восстановления. Как видите, это очень просто, достаточно набрать несколько команд в терминале. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Remove Directory in Linux – How to Delete a Folder from the Command Line
Zaira Hira
Linux CLI is a powerful tool that can help you accomplish complex tasks.
One of the common operations you’ll need to perform is to delete things. Just as like creating files and folders, deleting them from the Linux command line is something you’ll do often.
In this post, we will discuss how to delete directories from the command line. We will discuss the syntax along with some examples. I am using Ubuntu in these examples.
Syntax of the Linux rm Command
You use the rm command to delete something from the command line in Linux. The syntax of the rm command looks like this:
Some important flags you’ll need to use when deleting a directory are as follows:
- -r , -R , —recursive [«Recursion»] – Removes directories and their contents recursively.
- -v , —verbose [«Verbose»] – This option outputs the details of what is being done on the CLI.
- -f , —force [«Force»] – This option ignores nonexistent files and never prompts you.
- -i [«Interactive»] – Use this flag when you want to be prompted before every removal.
- -d [«Directory] – This works only when the directory is empty.
⚠ Be careful when using the rm command️ and always make sure that any important data is backed up.
How to identify a folder to remove
As we are discussing how to delete folders, we need to be pretty sure that we are actually deleting a folder. We can identify a folder/directory with the d flag in the first column. Notice that files have the first flag as — .
Examples of Linux rm command
In our current folder, we have 2 folders CSharpLab and PythonLab . Their content is shown below.
Note that CSharpLab is an empty directory.
How to delete a folder that’s not empty
Let’s delete the PythonLab folder first.
- -r recursively deletes all files and folders. Note in the output below, all files ( man.py, calculator.py, palindrome.py ) and folders ( /lib ) were removed.
- -v shares details.
- -i makes deletion interactive, which means it will ask before removing anything.
How to delete an empty folder
Let’s try to delete the CSharpLab folder. As this folder is empty, we can use the -d flag.
How to use the -f «force» flag
Let’s now see how the -f flag works. This forces the deletion of folders without any prompts or warnings. In case of an error, -v still ignores, and deletes the files that are valid.
In the example below, there is a typo in the folder name. Note that the typo is ignored. The original file is intact.
Wrapping up
Removing directories is useful when you need to remove folders after archiving them, when deleting duplicates, when deleting unused folders, and much more.
All these tasks are targeted at creating more disk space. I hope you found this blog helpful.