Cmd delete file linux

Как удалить файл через терминал 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-ти дней.

Читайте также:  Ssh linux with private key

Чтобы полностью стереть файл, без возможности восстановления используйте команду shred. Во время удаления файлов с помощью утилиты rm удаляется только ссылка на файл, само же содержимой файла по-прежнему находиться на диске, пока система не перезапишет его новыми данными, а пока этого не случится файл можно легко восстановить. Принцип действия утилиты такой — после удаления файла, его место на диске несколько раз перезаписывается.

Опцией -n — можно указать количество перезаписей диска, по умолчанию используется 3. А если указать опцию -z программа при последней перезаписи запишет все нулями чтобы скрыть, уничтожение файла.

Выводы

Вот и все. Теперь вы знаете как удалить файл в Ubuntu, как видите, делать это не так уж сложно. Если у вас остались вопросы, пишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Use rm to Delete Files and Directories on Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

This guide shows how to use rm to remove files, directories, and other content from the command line in Linux.

To avoid creating examples that might remove important files, this Quick Answer uses variations of filename.txt . Adjust each command as needed.

The Basics of Using rm to Delete a File

rm filename1.txt filename2.txt 

Options Available for rm

-i Interactive mode

Confirm each file before delete:

-f Force

-v Verbose

Show report of each file removed:

-d Directory

Note: This option only works if the directory is empty. To remove non-empty directories and the files within them, use the r flag.

-r Recursive

Remove a directory and any contents within it:

Combine Options

Options can be combined. For example, to remove all .png files with a prompt before each deletion and a report following each:

remove filename01.png? y filename01.png remove filename02.png? y filename02.png remove filename03.png? y filename03.png remove filename04.png? y filename04.png remove filename05.png? y filename05.png

-rf Remove Files and Directories, Even if Not Empty

Add the f flag to a recursive rm command to skip all confirmation prompts:

Combine rm with Other Commands

Remove Old Files Using find and rm

Combine the find command’s -exec option with rm to find and remove all files older than 28 days old. The files that match are printed on the screen ( -print ):

find filename* -type f -mtime +28 -exec rm '<>' ';' -print 

In this command’s syntax, <> is replaced by the find command with all files that it finds, and ; tells find that the command sequence invoked with the -exec option has ended. In particular, -print is an option for find , not the executed rm . <> and ; are both surrounded with single quote marks to protect them from interpretation by the shell.

This page was originally published on Tuesday, July 3, 2018.

Источник

How to Remove (Delete) a File or Directory in Linux

tutorial on removing linux Files and Directories using the command line

Note: If you feel that a directory is misplaced and you do not want to remove it, try moving it to a different place. To learn how, visit our post How to Move Directories in Linux.

Читайте также:  What is my locale linux

How To Remove or Delete Linux Files

The rm command deletes files in a Linux. The command unlinks the data from the file name, allowing the user to overwrite on that particular storage space.

To delete a single file, entering the following in the command line:

The rm command can be used to delete more than one file at a time:

rm filename_1 filename_2 filename_3

Wildcards can be used with this command.

For example, to delete all files with the .bmp filename, enter:

This method is also used to delete all files that contain a string of characters:

This will erase any file that has the word sample in the name.

The system will search the current directory for the file you want to remove.

To delete a file in a different directory, either switch to that directory first:

Or you can specify the file location in a single command directly:

Note: Once the rm command has deleted a file, you will not be able to access it. The only way to retrieve a file would be to restore it from a backup (if one is available).

rm Command Options

You can adjust the way the rm command works by adding options. An option is a hyphen, followed by one or more letters that stand for commands.

If you’re deleting multiple files, add a confirmation prompt. Use the –i option to use an interactive dialog:

Confirm the deletion of files by typing ‘yes’ or ‘no.’

Terminal asks for confirmation before removing file.

To display the progress of the deletion with the v or verbose command:

The output confirms that the file test.txt has been successfully removed.

Confirmation that the test.txt file has been removed.

To force the removal of a file that’s write-protected, use the –f option:

To use sudo privileges for a file that says Access denied and delete it:

Note: Read about sudo rm -rf and why it is a dangerous Linux command.

How to Delete a Directory in Linux

A linux directory (or folder) can be empty, or it can contain files. To remove a directory in Linux, use one of the following two commands:

  • rmdir command – removes empty directories/folders
  • rm command – removes a directory/folder along with all the files and sub-directories in it

Remove Directory Linux with rm Command

By adding the -r (-R) option to the rm command, you can remove a directory along with all its contents.

To remove a directory (and everything inside of it) use the –r option as in the command:

This will prompt you for confirmation before deleting.

To remove a directory without confirmation:

Also, you can delete more than one directory or folder at a time:

rm –r dir_name1 dir_name2 dir_name3

Remove Directories in Linux with rmdir Command

Remember, the rmdir command is used only when deleting empty folders and directories in Linux. If a specified directory is not empty, the output displays an error.

The basic syntax used for removing empty Linux folders/directories is:

Additionally, you can delete multiple empty directories at once by typing:

rmdir [dir_name1][dir_name2][dir_name3]

If the command finds content in one of the listed directories, it will skip it and move on to the next one.

Note: To permanently delete a file in Linux by overwriting it, use the shred command.

Читайте также:  Detect memory leak in linux

With this tutorial, deleting files and directories in Linux was made easy. The rm and rmdir commands are flexible with many options available.

Vladimir is a resident Tech Writer at phoenixNAP. He has more than 7 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His articles aim to instill a passion for innovative technologies in others by providing practical advice and using an engaging writing style.

The find command is a useful command-line tool in Linux. It allows you to use the terminal to search for a.

If a Linux process becomes unresponsive or is consuming too many resources, you may need to kill it. Most.

The chown command changes user ownership of a file, directory, or link in Linux. Every file is associated.

Want to learn how to copy files in Linux OS? This guide will show you how to use the Linux commands to copy.

Источник

How to Delete Files and Directories Using Linux Commandline

Delete file or Folder

In this tutorial, we will learn how to delete files and folders using the command line on Linux. This tutorial is compatible with all Linux distributions, so it works in the same way on Ubuntu, Debian, CentOS, AlmaLinux, Rocky Linux, etc. So, let’s get started.

Delete a File on Linux

In Linux rm command is used to remove files and folders on the command prompt. Navigate to that specific directory where the file exists that you want to remove. The rm command is basically the equivalent of the del command on Windows. Specify the location otherwise, it will start looking in the current working directory. I have a file under the /tmp/ folder which I want to delete. To delete the desired file open up the terminal and type the following command:

Delete a single file - cmd remove file

Be careful, while files and folders from Linux because once deleted, they can’t be rolled back. For this use –i, it will ask you for confirmation before deleting the file:

Confirm file delete

If you do not want a confirmation message for deletion, use the following command:

Force delete file on Linux

It will not prompt the confirmation message.

Delete Multiple Files on Linux

To delete multiple files on Linux, we can use the same command rm.

# rm file.txt file1.txt file2.txt

Delete two or more files on Linux

This will delete all the files.

Delete Directory on Linux

To delete a directory on Linux, the same command is used. But you need to add -r and -f options to delete a directory.

Delete directory

But be careful, this deletes the directory recursively with all files and folders inside. You can use the above without -f, as it will not prompt for confirmation. -r option is used for deleting the directory.

If you just want to remove a directory that is empty, use this command instead:

The command will show an error in case the directory is not empty.

Summary

  • In all Linux distributions, rm command is used to delete the files and folder.
  • If -i is used with rm, it will prompt for the confirmation before deleting.
  • If -r is used with rm, it will delete the directory.

About This Site

Vitux.com aims to become a Linux compendium with lots of unique and up to date tutorials.

Latest Tutorials

Источник

Оцените статью
Adblock
detector