Removing files linux command

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

Читайте также:  Linux on limbo pc emulator

Будет выполнено удаление файлов через терминал все файлы в папке старше 5-ти дней.

Чтобы полностью стереть файл, без возможности восстановления используйте команду 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 Delete a File or Directory in Linux – Command to Remove a Folder and its Contents

Shittu Olumide

Shittu Olumide

Читайте также:  Linux как создать tar архив

How to Delete a File or Directory in Linux – Command to Remove a Folder and its Contents

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:

  1. 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.
  2. 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».
  3. 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.
  4. 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.
  5. 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.
Читайте также:  Adding ssh key to linux

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:

  1. 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.
  2. 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».
  3. 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.
  4. 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.

  1. Be careful when using the rm command with the -r or -R option as it can delete files and directories irreversibly.
  2. Always double-check the file or directory name before deleting to avoid accidentally deleting the wrong file or directory.
  3. Use the shred command only when necessary, as it can take longer to delete files than other methods.
  4. 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.

Источник

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