Как удалить файл через терминал Linux
Эта небольшая заметка ориентирована на совсем начинающих. Сегодня мы рассмотрим как удалить файл linux через терминал. Для более опытных пользователей это элементарная задача, но новичкам надо с чего-то начинать. Знать как работать с файлами в консоли очень важно.
К тому же удаление из консоли дает много преимуществ и большую гибкость. Например, с помощью специальной команды вы можете полностью стереть файл с жесткого диска, так что его уже ни за что невозможно будет восстановить или одной командой с помощью специальных символов, условий или регулярных выражений удалить сотни ненужных файлов в одном каталоге или подкаталогох соответствующих определенному критерию.
В Linux для удаления файлов предусмотрена стандартная утилита rm. Как и все остальные, стандартные утилиты в имени rm тоже заложена определенная идея. Это сокращение от английского слова Remove.
Удаление файлов в Linux
Чтобы удалить файл linux достаточно передать в параметрах команде адрес файла в файловой системе:
Чтобы удалить все файлы, начинающиеся на слово file можно использовать специальный символ *, означает любой символ в любом количестве:
Эта команда удаления файла в linux должна использоваться очень осторожно, чтобы не удалить ничего лишнего. В утилиты есть опция -i, которая заставляет программу спрашивать пользователя перед тем, как удалить файл linux:
rm: удалить пустой обычный файл «/home/user/file»?
Если файлов очень много, вы уверены в правильности команды и отвечать каждый раз y неудобно, есть противоположная опция — f. Будут удалены все файлы без вопросов:
Для удаления директорий, вместе с файлами и поддиректориями используется опция -R, например:
Будет удалено все что находиться в папке 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, как видите, делать это не так уж сложно. Если у вас остались вопросы, пишите в комментариях!
How to Remove Files and Directories Using Linux Command Line
Updated Sep 1, 2019
In this tutorial, we will show you how to use the rm , unlink , and rmdir commands to remove files and directories in Linux.
How to Remove Files #
To remove (or delete) a file in Linux from the command line, use either the rm (remove) or unlink command.
The unlink command allows you to remove only a single file, while with rm you can remove multiple files at once.
Be extra careful when removing files or directories, because once the file is deleted, it cannot be easily recovered.
To delete a single file, use the rm or unlink command followed by the file name:
If the file is write-protected, you will be prompted for confirmation, as shown below. To remove the file type y and hit Enter . Otherwise, if the file is not write-protected, it will be deleted without prompting.
To delete multiple files at once, use the rm command followed by the file names separated by space.
You can also use a wildcard ( * ) and regular expansions to match multiple files. For example, to remove all .pdf files in the current directory, use the following command:
When using regular expansions, first list the files with the ls command so that you can see what files will be deleted before running the rm command.
Use the rm with the -i option to confirm each file before deleting it:
To remove files without prompting even if the files are write-protected pass the -f (force) option to the rm command:
You can also combine rm options. For example, to remove all .txt files in the current directory without a prompt in verbose mode, use the following command:
How to Remove Directories (Folders) #
In Linux, you can remove/delete directories with the rmdir and rm .
rmdir is a command-line utility for deleting empty directories while with rm you can remove directories and their contents recursively.
To remove an empty directory, use either rmdir or rm -d followed by the directory name:
To remove non-empty directories and all the files within them, use the rm command with the -r (recursive) option:
If a directory or a file within the directory is write-protected, you will be prompted to confirm the deletion.
To remove non-empty directories and all the files without being prompted, use rm with the -r (recursive) and -f options:
To remove multiple directories at once, use the rm -r command followed by the directory names separated by space.
Same as with files you can also use a wildcard ( * ) and regular expansions to match multiple directories.
Conclusion #
By now you should have a good understanding of how to use the Linux rm , rmdir and unlink commands and you should be able to safely remove files and directories from the command line.
Linux / UNIX Delete a file
Syntax: rm command to remove a file
rm (short for remove) is a Unix / Linux command which is used to delete files from a filesystem. Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). The syntax is as follows to delete the specified files and directories:
- -f : Forcefully remove file
- -r : Remove the contents of directories recursively
When rm command used just with the file names, rm deletes all given files without confirmation by the user.
Warning : Be careful with filenames as Unix and Linux, by default, won’t prompt for confirmation before deleting files. Always keep verified backups of all critical files and data.
Unix Remove or delete a file example
Say you have a file named abc.txt and you want to remove it:
$ rm abc.txt
Linux delete multiple files
Delete three files named foo.mp4, bar.doc, and demo.txt, run:
rm foo.mp4 bar.doc demo.txt ls
Linux recursively delete all files
Remove all files and sub-directories from a directory (say deltree like command from MS-DOS world), enter:
$ rm -rf mydir
Linux delete a file and prompt before every removal
To request confirmation before attempting to remove each file pass the -i option to the rm command:
$ rm -i filename
Sample outputs:
Gif 01: rm command demo
Force rm command to explain what is being done with file
Pass the -v option as follows:
$ rm -v moiz.list.txt bios-updates.doc
removed ‘moiz.list.txt’
removed ‘bios-updates.doc’
How to delete empty directories
To remove empty directory use rmdir command and not the rm command:
$ rmdir mydirectory
$ rmdir dirNameHere
$ rmdir docs
How to read a list of all files to delete from a text file
The rm command is often used in conjunction with xargs to supply a list of files to delete. Create a file called file.txt:
$ cat file.txt
List of to delete:
Now delete all file listed in file.txt, enter:
$ xargs rm
How do I delete a file named -foo.txt or a directory named -bar?
To delete a file called -foo.txt :
rm — -foo.txt
OR
rm — ./-foo.txt
To delete a directory called -bar :
rm -r -f — -bar
The two — dashes tells rm command the end of the options and rest of the part is nothing but a file or directory name begins with a dash.
Never run rm -rf / as an administrator or normal UNIX / Linux user
$ rm -rf /
$ rm -rf *
rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Unix disasters. The rm -rf / variant of the command, if run by an administrator, would cause the contents of every writable mounted filesystem on the computer to be deleted. Do not try these commands.
Conclusion
You learned how to delete files on Linux and Unix-like operating systems. Here are all important options for GNU rm command (read man page here)