Что такое папка lost + found в Linux и macOS?
Папка lost + found является частью Linux, macOS и других UNIX- подобных операционных систем. Каждая файловая система, то есть каждый раздел, имеет свой собственный каталог lost + found. Вы найдете восстановленные биты поврежденных файлов здесь.
Что потерял + нашел Для
В Linux команда fsck — сокращение от «проверка файловой системы» — проверяет ваши файловые системы на наличие ошибок. fsck может найти биты «потерянных» или поврежденных файлов в файловой системе. Если это так, fsck удаляет эти поврежденные биты данных из файловой системы и помещает их в папку lost + found.
Например, если вы внезапно выключили компьютер во время его работы и файлы были записаны на жесткий диск, инструмент fsck может автоматически проверить вашу файловую систему при следующей загрузке компьютера. Если он находит какие-либо поврежденные данные, он помещает их в папку lost + found файловой системы.
Это работает аналогично в MacOS. Если вы запустите Disk Utility и проверите свой диск на наличие проблем с файловой системой, он может найти поврежденные биты данных и сохранить их в папке lost + found.
Большинство файловых систем UNIX имеют папку lost + found, включая ext2, ext3 и ext4 в Linux, а также файловую систему HFS + в macOS. Некоторые файловые системы могут не использовать папку lost + found, но они менее распространены в этих операционных системах.
Где вы найдете потерянные + найденные папки
Каждая файловая система имеет свою собственную папку lost + found, так что вы найдете ее на каждом жестком диске или в разделе. Это означает, что вы найдете папку lost + found в корневом каталоге, например, в / lost + found.
Если у вас смонтированы другие разделы, вы также найдете папку lost + found на каждом из них. Например, если у вас есть отдельный раздел для вашего домашнего каталога, смонтированный в / home, вы найдете папку lost + found в / home / lost + found. Потерянные данные из домашнего раздела будут помещены в / home / lost + found вместо / lost + found.
Если у вас есть USB-накопитель или другой внешний накопитель, отформатированный в файловой системе Linux, вы также увидите на нем каталог lost + found.
Эта папка часто скрыта, поэтому вам может потребоваться показать скрытые файлы и папки, чтобы увидеть ее.
Как просмотреть содержимое утерянной + найденной папки
Эта папка, как правило, доступна только пользователю root, что не позволяет обычным пользователям заглядывать внутрь и получать доступ к восстановленным данным, к которым у них обычно нет прав доступа. Не думайте, что поврежденные файлы лежат вокруг только потому, что вы видите папку lost + found — во многих системах она может быть пустой.
Чтобы увидеть, что внутри, откройте окно терминала и последовательно выполните следующие команды:
(Если первая команда не работает, попробуйте запустить su вместо sudo su каждый дистрибутив Linux немного отличается.)
Терминал перечислит любые файлы в папке lost + found. Если ничего не возвращается, папка пуста.
Восстановление данных часто сложно
Если что-то находится в папке lost + found, обычно это не целые файлы. Вместо этого вы увидите небольшие фрагменты файлов или фрагменты поврежденных данных, и вы не сможете ничего с ними сделать.
Если вы не потеряли важные данные, вам, вероятно, не нужно беспокоиться о том, что находится в папке lost + found. Если вы потеряли данные, вы можете просмотреть папку lost + found и попытаться восстановить часть из них. Если вы найдете здесь полный файл, вы можете попытаться переместить файл обратно в исходное местоположение и использовать его. Но есть небольшая вероятность, что вы можете сделать что-нибудь с поврежденными частичными файлами. Команда fsck поместила их туда на всякий случай.
Вы также не можете удалить папку lost + found, так как это постоянная часть файловой системы. Однако, если вы найдете бесполезные фрагменты файлов внутри папки lost + found, которые вы не можете собрать вместе, вы можете удалить их с помощью терминала, чтобы освободить место.
What is the purpose of the lost+found folder in Linux and Unix?
What is it for? Under what circumstances would I interact with it? How would I interact with it?
3 Answers 3
If you run fsck , the filesystem check and repair command, it might find data fragments that are not referenced anywhere in the filesystem. In particular, fsck might find data that looks like a complete file but doesn’t have a name on the system — an inode with no corresponding file name. This data is still using up space, but it isn’t accessible by any normal means.
If you tell fsck to repair the filesystem, it will turn these almost-deleted files back into files. The thing is, the file had a name and location once, but that information is no longer available. So fsck deposits the file in a specific directory, called lost+found (after lost and found property).
Files that appear in lost+found are typically files that were already unlinked (i.e. their name had been erased) but still opened by some process (so the data wasn’t erased yet) when the system halted suddenly (kernel panic or power failure). If that’s all that happened, these files were slated for deletion anyway, you don’t need to care about them.
Files can also appear in lost+found because the filesystem was in an inconsistent state due to a software or hardware bug. If that’s the case, it’s a way for you to find files that were lost but that the system repair managed to salvage. The files may or may not contain useful data, and even if they do they may be incomplete or out of date; it all depends how bad the filesystem damage was.
On many filesystems, the lost+found directory is a bit special because it preallocates a bit of space for fsck to deposit files there. (The space isn’t for the file data, which fsck leaves in place; it’s for the directory entries which fsck has to make up.) If you accidentally delete lost+found , don’t re-create it with mkdir , use mklost+found if available.
The lost+found Directory in Linux and UNIX
The Linux fsck system utility is directly associated with the lost+found directory construct. Executing the fsck system utility will initiate a filesystem check and repair routine.
The result of using the fsck system utility might lead to the retrieval of data fragments, not ‘registered/referenced’ by the Linux filesystem.
For instance, fsck tends to highlight data that resembles a complete file but missing a name record on the Linux system. Therefore, such nameless data tend to use up system memory and remain mysterious since there are no conventional means of accessing it.
This article is here to unravel the mysteries behind the lost+found directory and its association with the Linux fsck utility.
The lost+found Directory and the fsck Command
According to its manual page, the fsck system utility is primarily used to check and repair a questionable filesystem on a Linux operating system environment. One of its roles is to find almost-deleted files and transform them into recognizable files.
We could say that it deals with files whose name and location entries are no longer valid. So once the fsck utility retrieves such files, its go-to location for their immediate storage is the lost+found directory.
We could therefore characterize files existing in the lost+found directory as unlinked (since they have no name and location) yet being used by a system process (probably due to power failure or kernel panic) after a sudden system halt. The Linux system attributes data stored in the lost+found directory as obsolete.
The fsck utility is responsible for the creation of this lost+found directory at the root level of the Extended File System volume (Whether it’s a single volume or a volume partition).
Linux lost+found Directory
Therefore, on the root level of each of your Linux volume partitions, a lost+found directory exists.
Understanding lost+found Directory in Linux
Consider the instance where a process has access to a file and another process ends up deleting the file before it is released by the other process. The existence of this file is classified as a data fragment since its name and location entries no longer exist.
The fsck utility then repossesses this fragmented data and transforms it into a new file before moving it to the lost+found directory.
Now, whenever a software bug or hardware issue occurs and damages the Linux filesystem, running the fsck utility retrieves the assumed-deleted files that are now under a new identity in the lost+found directory.
The data on these lost+found directory files are then retrieved and used as a prognosis for the damaged Linux filesystem problem.
Creating lost+found Directory in Linux
For some reason (before coming across this article) you might have found the existence of the lost+found directory questionable and decided to delete it. It is not recommended to use the mkdir command to recreate this directory.
Instead, execute the mklost+found command:
Run the mklost+found command on the root level of your Linux partition since it automatically preallocates the fsck utility some space instead of this utility (fsck) allocating itself the needed data blocks during data recovery and leading to data corruption.
Recovering lost+found Directory Data
The first step is to identify the partition that has issues e.g /dev/sdb4. You could use the lsblk command to identify the partition label.
The next step is to unmount the partition or make sure it is unmounted.
Execute the fsck command as root or sudoer user:
Run fsck on Partition
Create a mounting point and mount the partition:
Switch to the mounted directory:
You should be able to see the lost+found directory.
If your filesystem had issues, then recoverable data should be found here.
If you need to get rid of the lost+found directory data that you no longer need on all active partitions on your system, execute the following find command:
We now know everything there is to know about the Linux lost+found directory. Your comments and feedback will be appreciated.
Почему появилась директория lost+found на отформатированном диске в чистом Ubuntu?
Установлен чистый Ubuntu сервер версии 20. Два HDD переразмечены утилитой fdisk:
- удалены все разделы
- созданы таблицы GPT
- созданы разделы во весь диск
Разделы форматированы mkfs.ext4
В fstab добавлены эти диски по аналогии с теми, что прописал установщик:
Ожидалось, что диски будут стоять молча, но после монтирования на них началась активность и появились директории lost+found . Отмонтировать диски нельзя, потому что они заняты.
Откуда появилась активность и эти директории на чистой системе и чистых дисках?