Del file in 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-ти дней.

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

Читайте также:  Get proc info linux

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

Выводы

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

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

Источник

How to Delete a File in Ubuntu

Removing or deleting a file in a Linux system is a fundamental task that every user wants to perform this action frequently. Deleting unnecessary files creates an extra space on your system that a user can utilize for installing a new package or can save new files.

If you are a new Ubuntu user and don’t know how to delete a file or multiple files in Ubuntu using the command line or via the GUI, we will cover in this article all details about how to remove or delete a file in Ubuntu. It is important to note that you need certain writable permissions to delete a file in the Ubuntu Linux system.

Methods to Remove or Delete Files in Ubuntu

Using the following two different methods, you can delete or remove a file in the Ubuntu Linux system:

  • Delete or remove a file in Ubuntu using Terminal
  • Delete a file using the Graphical user interface

Important Note: You must be extra careful before deleting a file from your Ubuntu system. Once the file is deleted from the system, it would be hard to recover its content.

Method 1: Delete or Remove a File in Ubuntu Using Terminal

Using this method, you can remove a file using the command line application ‘Terminal’. Two Linux commands are available to delete or remove a file in Ubuntu distribution. First is the ‘Unlink’ command but, you can delete only a single file using this command.

The other most popular is the ‘rm’ command shortly used for “remove”, which is used to delete a file in the Ubuntu Linux system. Using the ‘rm’ command, you can delete multiple files at once from your Ubuntu system.

To delete or remove a file using the unlink command, type the unlink command followed by the name of the file which you want to delete. The syntax of the unlink command is mentioned below:

Example

For example, we want to remove a text file with the name ‘demo.txt’ from the Ubuntu system. Using the above ‘unlink’ command, you can easily delete this file from your system as follows:

Delete or Remove a File Using the rm Command

Using the rm command, you can delete single or multiple files in the Ubuntu system. To delete a file using the ‘rm’ command, use the following syntax:

Example

For example, we want to remove a text file from the system ‘Downloads’. To do this task, use the rm command followed by the file path as follows:

If you delete a write-protected file from the Ubuntu system, the prompt displays on the terminal screen for confirmation, enter ‘y’ and then press the ‘Enter’ key. Otherwise, the file will be deleted from your system without displaying any confirmation prompt.

Читайте также:  Управление доменными пользователями linux

Delete multiple files using the rm command

You can also delete multiple files from the Ubuntu system using the ‘rm’ command. To remove multiple files, you must have certain write permissions on the files. To remove or delete multiple files from your system, use the ‘rm’ command and specify the file names which will be separated by a space as follows:

Delete multiple similar files using the wildcard (*)

You can also remove the multiple match file in the current directory using the regular expansions or wildcard(*).

For example, to delete all ‘.txt’ files from the current working directory. Execute the rm command by using the wildcard with the .txt extension as follows:

Options with rm Command

The following options can use along with the rm command:

Options Description
-f The ‘-f’ option deletes all read-only files immediately from your system without displaying any confirmation prompt.
-i The ‘-i’ option prompts a user for confirmation before deleting or removing a file.
-v The ‘-v’ option displays the file names on the terminal screen as the file is being processed or deleted from the system.
-I The ‘-I’ options show user prompts whenever the user attempts to delete three files at a time. This option also can be used when you are deleting files recursively.
-R or -r The both options ‘-R’ and ‘-r’ delete the current directory along with all subdirectories and files.
-q The ‘-q’ option suppresses all warnings. However, the error messages are still displayed on the screen.

How to Use rm Command Options?

We discussed a few examples here related to ‘rm’ command options, which are given below:

Type the ‘rm’ command followed by the option ‘-i’ that each time confirms before deleting a file:

If you delete a file without displaying a user confirmation prompt, even if the files are write-protected then, use the ‘rm’ command followed by the option ‘-f’.

You can also combine rm command options for deleting a file. For example, to delete all matched files from the current directory without prompt a verbose. Use the ‘rm’ command and also mention the ‘-fv’ option as follows:

Important Note:
Never execute the ‘sudo rm -R /’ or ‘sudo rm -r /’ commands as root or normal user on your system. These commands are harmful to your data because these commands delete or remove all root directory files and will also delete all mounted volumes. Don’t even try to run the ‘sudo rm -rf /*’ command on your system. It does blunders with your system.

Method 2: Delete a File Using the Graphical User Interface

To delete a file using the GUI, you should have writable permissions on the file and you must be logged in as a root user on your Ubuntu system. By following few simple steps, you can easily delete a file or multiple files from the Ubuntu system:

Go into the Ubuntu file system and right-click on a file that you want to delete from your system.

To delete the selected file, choose ‘move to trash’ from the displayed dropdown list.

To permanently remove from the ‘Trash’ folder, right-click on the Trash and then choose the ‘empty trash’.

Читайте также:  Install virtualbox extensions linux

Conclusion

We learned how to delete files in the Ubuntu Linux system. Moreover, we have also seen some files we cannot delete using GUI but these type of files you can delete via the command line by executing commands as a root user.

About the author

Samreena Aslam

Samreena Aslam holds a master’s degree in Software Engineering. Currently, she’s working as a Freelancer & Technical writer. She’s a Linux enthusiast and has written various articles on Computer programming, different Linux flavors including Ubuntu, Debian, CentOS, and Mint.

Источник

What happens when you delete a file in Linux?

Understanding how the rm command works helps you make informed decisions about how you trash, delete, or shred files.

Crumpled yellow paper with a metal trash basket

Modern desktop and graphical environments offer a trash folder. This location permits retrieving a «deleted» file before it is irrecoverably erased. When you’re using a terminal, trash commands send files to the trash folder as a staging area. But what happens when you tell your Linux computer to delete a file with the rm command? Does it delete the file?

[ Keep your most commonly used commands handy with the Linux commands cheat sheet. ]

File removal

Different interactions occur when you delete a file, mainly depending on the filesystem (EXT4, XFS, BtrFS, and so on) the system uses. Without dwelling on filesystem specifics, it’s always possible to monitor exactly what happens when you invoke the rm command.

First, create a test file named example.txt :

$ echo "This is a test file" > example.txt

Get some additional information about the file with the stat command:

$ stat example.txt File: example.txt Size: 26 Blocks: 8 IO Block: 4096 regular file Device: fd00h/64768d Inode: 17198515 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 1001/testuser) Gid: ( 1001/testuser) Context: unconfined_u:object_r:user_home_t:s0 Access: 2022-09-14 17:22:51.492026903 +0200 Modify: 2022-09-14 17:24:21.667609795 +0200 Change: 2022-09-14 17:24:21.667609795 +0200 Birth: 2022-09-14 17:22:51.492026903 +0200

The stat command output displays the filesystem’s block size, how many blocks the file uses, and so on. (Don’t worry, this article does not require any math!)

The most important information in this example is the inode number. In this example, that’s:

What is an inode?

An inode holds metadata about a file. It includes the file’s size, where to find the blocks that contain the file’s contents, the file mode, and so on. Every file has a reference inode.

There are tools to find block information about a file. These commands are specific to the filesystem. For example, in XFS, it is the xfs_bmap command.

$ xfs_bmap example.txt example.txt: 0: [0..7]: 9343608..9343615

Remember those numbers. If you proceed with deletion, you’re going to need them!

The strace command

A system call («syscall» for short) is the programmatic way a program requests a service from the kernel. Strace is a powerful tool that allows you to trace the thin layer between user processes and the Linux kernel. To understand the interaction between the file and the syscall you make with rm , you can monitor the deletion process with strace :

$ strace --follow-forks \ --absolute-timestamps \ --syscall-times \ --no-abbrev \ --decode-fds -o /tmp/rm_log.txt \ --string-limit 1024 \ rm example.txt

Using /tmp/rm_log.txt as a record, you can see important information about the rm process execution. First, notice the process ID (PID):

1727 [. ] execve("/usr/bin/rm", ["rm", "example.txt"],

You can also see that the system verifies the stat of the file with the syscall newfstatat :

1727 17:26:04.489674 newfstatat(AT_FDCWD, "example.txt", , AT_SYMLINK_NOFOLLOW) = 0

Источник

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