Remove Directory in Linux: How to Delete Files and Folders
Learning how to use the Linux command line is essential for all Linux users and system administrators. Simple maintenance tasks like creating a file, navigating to a folder, or moving a file can all be done through it.
Since Linux is a popular operating system for virtual server hosting, understanding fundamental Linux commands is crucial for server management.
This article will show you how to remove files and directories using the Linux command line.
How to Remove a Directory in Linux
To permanently remove a directory in Linux, use either the rmdir or rm command:
- Use the rmdir or rm -d command to remove empty directories.
- Use the rm-r command to remove non-empty directories.
Before you remove a directory, you need to know the name of it. To discover files and directories, use the ls command, and to know the current directory you are in, use the pwd command.
The options you use together with these commands are also important to determine how they work. Here’s a quick recap of rm command options:
How to Remove an Empty Directory (rmdir Command)
In the Linux environment, files and directories will be permanently deleted as there’s no recycle bin or trash folder where you can retrieve them. If you delete a file or directory in Linux by mistake, the only way to recover it is from a backup.
Using the rmdir command prevents such unwanted actions as it only works for empty directories. It will return the following error message if the directory contains files:
rmdir: failed to remove ‘Directory’: Directory not empty
The syntax for the rmdir command is as follows:
rmdir [option] DirectoryName
If you don’t want to use any command line option, remove it from the syntax. Remember that the command line is case-sensitive. Therefore, if the folder name contains uppercase letters, type it accordingly.
For example, here’s a command for deleting the Simple-Directory folder:
The rmdir command also works for multiple empty directories. Add the directories in the command as additional arguments to delete multiple directories in Linux.
rmdir Directory_1 Directory_2 Directory_3
Now let’s see options you can use with the rmdir command. The first one is -p, which works for deleting a subdirectory and its parent directory. For example, if your directory path is /Directory/SubDirectory, use the following command:
rmdir -p /Directory/SubDirectory
This command will delete the SubDirectory folder in the Directory path first. Then, if the Directory folder is empty after the SubDirectory was removed, the folder will also get deleted.
The next option is verbose, represented with -v in the command line. This option will print a text as a confirmation that the specified directory has been deleted. Here’s an example of this command:
rmdir -v Simple-Directory
The output message will be like this:
rmdir: removing directory, ‘Simple-Directory’
How to Remove a Non-Empty Directory (rm Command)
Now let’s see how to remove non-empty directories using the rm command. This command is originally used to remove files, but we can use it to remove directories using options like -r, -rf, and -d. The basic syntax for the rm command is as follows:
rm [option] FileOrFolderName
Use a recursive option, represented by -r, to remove the directory and its content. The following command shows how to delete Simple-Directory and its content:
rm -r Simple-Directory
Warning! If you delete a non-empty directory using the rm -r command, all the files inside it will be permanently deleted, and you can only recover them from a backup. Execute this command with caution.
If the directory is write-protected, you will be prompted to confirm before proceeding with the directory removal. To delete a directory without being prompted, use the -rf option.
rm -rf Simple-Directory
The rm command also works for removing empty directories in Linux. However, unlike the rmdir command, you have to use the -d option.
rm -d Simple-Directory
Just as with the rmdir command, you can use the rm command to remove multiple directories. Add directory names as new arguments in the command line:
rm -r Directory_1 Directory_2 Directory_3
How to Delete a File With the rm Command
You may want to use the rm command to manually remove files instead of deleting a non-empty folder straight away. This method is safer as it prevents removing important files accidentally.
To delete a single file in the current working directory, use the rm command followed by the file name:
To delete multiple files in the directory, write all the file names you want to delete in the command:
rm file1.txt file2.txt file3.txt
All the commands above work if you are in the same directory as the specified files. However, you can put the file path into the command line argument to delete a file that’s not in your current working directory.
Since the files will be permanently removed, you can add the -i option in the command to make the terminal prompt you to confirm every file deletion. This way, you prevent unpleasant mistakes from happening.
rm -i file1.txt file2.txt file3.txt
Type Y and press Enter if you want to delete the file, or type N and press Enter if you don’t.
Use -I instead to get prompted only once before deleting more than three files. While this is less safe than the -i option, it still gives extra protection to avoid deleting important files.
rm -I file1.txt file2.txt file3.txt
However, the system will prompt you anyway before removing files if they’re write-protected. If you don’t want to get prompted when deleting such files, use the -f option.
The commands we’ve discussed so far will delete specific files. However, using wildcards, you can delete multiple files with a single command. There are two types of wildcards – the asterisk (*) and the question mark (?).
The asterisk represents multiple unknown characters, and one of the most common use examples is deleting files with a certain extension. The command below will delete all .txt files in the current working directory:
You can also use the asterisk to delete all files beginning with a specific letter.
In the example above, the asterisk represents all unknown characters that come after the letter a. The command will delete all files beginning with a regardless of their extensions, such as amazon.txt, alligator.png, and aaron.zip.
The question mark wildcard, on the other hand, represents a single character. In conjunction with the asterisk wildcard, you can use it to delete files with a single character extension, such as .S, .O, and .C.
Warning! Be careful when using wildcards, as you may end up deleting important files. First, check all the files in the directory using the ls command. Make sure that there are no important data or system files before using the wildcard command.
Conclusion
Deleting directories and files through the command line in Linux requires understanding the correct use of the rm and rmdir commands. To put it simply, the rm command works for files and non-empty directories, while the rmdir only works for empty folders.
Remember that there is no recycle bin or trash folder in Linux. Once you remove files and directories using the command line, they will be permanently deleted. Therefore, use these commands with caution or create a backup before deleting the files and folders on your VPS.
If you have additional questions, feel free to leave us a comment.
Learn More Linux Commands for File Management
Linux Remove Directory FAQ
How to Delete All Files and Folders in Linux?
For empty folders, use either the rmdir or rm -d commands followed by the name of the folder:
rm -d dirname
rmdir dirname
The rm command with -r dir can be used for folders that are not empty.
rm -r dirname
Ignas is a part of Hostinger’s Technical team. He takes care of server administration and monitoring with a particular focus on software virtualization. In his free time, he’s always up for a skiing or kayaking adventure or a board game night.
Leo is a WordPress fanatic and contributor. He likes keeping up with the latest WordPress news and updates, and sharing his knowledge to help people build successful websites. When he’s not working, he contributes to WordPress documentation team and pampers his dogs.
Introduction
This page describes how to delete files through terminal.
It is possible, though difficult, to recover files deleted through rm. See DataRecovery. If you want to permanently delete a file use shred.
Commands for deleting files
The terminal command for deleting file(s) is rm. The general format of this command is rm [-f|i|I|q|R|r|v] file.
rm removes a file if you specify a correct path for it and if you don’t, then it displays an error message and move on to the next file. Sometimes you may not have the write permissions for a file, in that case it asks you for confirmation. Type yes if you want to delete it.
Как удалить файл через терминал Linux
Эта небольшая заметка ориентирована на совсем начинающих. Сегодня мы рассмотрим как удалить файл linux через терминал. Для более опытных пользователей это элементарная задача, но новичкам надо с чего-то начинать. Знать как работать с файлами в консоли очень важно.
К тому же удаление из консоли дает много преимуществ и большую гибкость. Например, с помощью специальной команды вы можете полностью стереть файл с жесткого диска, так что его уже ни за что невозможно будет восстановить или одной командой с помощью специальных символов, условий или регулярных выражений удалить сотни ненужных файлов в одном каталоге или подкаталогох соответствующих определенному критерию.
В Linux для удаления файлов предусмотрена стандартная утилита rm. Как и все остальные, стандартные утилиты в имени rm тоже заложена определенная идея. Это сокращение от английского слова Remove.
Удаление файлов в Linux
Чтобы удалить файл linux достаточно передать в параметрах команде адрес файла в файловой системе:
Чтобы удалить все файлы, начинающиеся на слово file можно использовать специальный символ *, означает любой символ в любом количестве:
Эта команда удаления файла в linux должна использоваться очень осторожно, чтобы не удалить ничего лишнего. В утилите есть опция -i, которая заставляет программу спрашивать пользователя перед тем, как удалить файл linux:
rm: удалить пустой обычный файл «/home/user/file»?
Если файлов очень много, вы уверены в правильности команды и отвечать каждый раз y неудобно, есть противоположная опция — f. Будут удалены все файлы без вопросов:
rm -f /home/user/file*
Для удаления директорий, вместе с файлами и поддиректориями используется опция -R, например:
rm -Rf /home/user/dir
Будет удалено все что находиться в папке dir, и эта папка. Только будьте бдительны, чтобы не получился знаменитый патч Бармина:
Не стоит выполнять эту команду в своей системе, как видите, она удаляет все файлы в файловой системе Linux.
Удаление файла в linux также возможно с помощью утилиты find. Общий синтаксис find:
find папка критерий действие
Например, мы хотим удалить файл linux по имени:
find . -type f -name «file» -exec rm -f <> \;
Будут найдены все файлы с именем file в текущей папке и для них вызвана команда rm -f. Можно не вызывать стороннюю утилиту, а использовать действие delete:
find . -type f -name «file» -delete
Удалить все файлы в текущей директории, соответствующие определенному регулярному выражению:
find . -regex ‘\./[a-f0-9\-]\.bak’ — delete
Или удалить файлы старше определенного строка, может быть полезно для удаления старых логов:
find /path/to/files* -mtime +5 -exec rm <> \;
Будет выполнено удаление файлов через терминал все файлы в папке старше 5-ти дней.
Чтобы полностью стереть файл, без возможности восстановления используйте команду shred. Во время удаления файлов с помощью утилиты rm удаляется только ссылка на файл, само же содержимой файла по-прежнему находиться на диске, пока система не перезапишет его новыми данными, а пока этого не случится файл можно легко восстановить. Принцип действия утилиты такой — после удаления файла, его место на диске несколько раз перезаписывается.
Опцией -n — можно указать количество перезаписей диска, по умолчанию используется 3. А если указать опцию -z программа при последней перезаписи запишет все нулями чтобы скрыть, уничтожение файла.
Выводы
Вот и все. Теперь вы знаете как удалить файл в Ubuntu, как видите, делать это не так уж сложно. Если у вас остались вопросы, пишите в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Delete a File or Directory in Linux: It Doesn’t Have to Be Scary
It can be uncomfortable especially if you are just getting used to work with Linux.
This tutorial will help you get familiar with the command to delete files and directories in Linux.
How to Remove a File
Written by Claudio Sabato
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!