search
HomeSystem TutorialLINUXHow to recover deleted files in Linux system

How to recover deleted files in Linux system

Jan 14, 2024 pm 06:48 PM
linuxlinux tutorialRed Hatlinux systemlinux commandlinux certificationred hat linuxlinux video

Introduction When a user accidentally deletes a file that is still needed, in most cases, there is no easy way to retrieve or rebuild the file. Fortunately, there are ways to recover files. When a user deletes a file, the file does not disappear, it is just hidden for a period of time.

How it works is explained here. In a file system, there is something called a file allocation table, which keeps track of the location of files in storage units (such as hard drives, MicroSD cards, flash drives, etc.). When a file is deleted, the file system will perform one of two tasks in the file allocation table: mark the file's entry in the file allocation table as "free space" or delete the file's entry in the file allocation table, And the corresponding space is marked as free space. Now, if a new file needs to be placed on a storage location, the operating system will place the file in a location marked as empty. After the new file is written to this empty space, the deleted file disappears completely. When a deleted file needs to be recovered, the user must never operate on any file again, because if the "empty space" corresponding to the file is occupied, the file can never be recovered.

怎样在 Linux 系统中恢复被删除文件

How does recovery software work?

Most file systems just mark the space as empty (when deleting files). In these file systems, the recovery software looks at the file allocation table and then copies the deleted files to another storage unit. If the file is copied to other deleted storage units that need to be recovered, then the user may lose the desired deleted file.

File systems rarely erase entries in the file allocation table. If the file system does this, the recovery software is recovering the files. The recovery software scans the file headers in the storage unit. All files have a special encoding string located at the beginning of the file, also called a magic number. For example, the magic number for a compiled JAVA class file is "CAFEBABE" in hexadecimal. So, if you want to recover files of this type, the recovery software will look for “CAFEBABE” and copy the files to another storage unit. Some recovery software can look for a particular file type. If the user wants to recover a PDF file, the recovery software will look for the magic number “25504446” in hexadecimal, which happens to be “%PDF” in ASCII encoding. The recovery software will look for all the magic numbers and then the user can choose which deleted file to recover.

If part of a file is overwritten, the entire file will be damaged. Often the file can be recovered, but its contents may no longer be of any use. For example, recovering a corrupted JPEG file would be pointless because the picture viewer cannot produce an image from the corrupted file. Therefore, even if the user owns the file, the file will be useless.

Before we continue, some information below will help guide the recovery software to find the correct storage unit. All devices are mounted in the /dev/ directory. The name given to each device by the operating system (not the name given to each partition or device by the administrator) follows certain naming rules.

The name of the second partition of the first SATA hard drive will be sda2. The first letter of the name hints at the storage type, which in this case is SATA, but the letter "s" could also refer to SCSI, FireWire, or USB. The second letter "d" refers to disk. The third letter refers to the device number, i.e. the letter "a" refers to the first SATA and "b" refers to the second. The last number represents the partition. A device name without a partition number represents all partitions for that setup. For the example above, the corresponding name is sda . The first letter of the name may also be "h", which corresponds to PATA hard disk (IDE).

The following are some examples of naming rules. If a user has a SATA hard drive (sda), the device has 4 partitions - sda1, sda2, sda3 and sda4. The user deletes the third partition, but the fourth partition name, sda4, will remain unchanged until the fourth partition is formatted. The user then inserted a USB memory card (sdb) with a partition - sdb1-, added an IDE hard drive with a partition - hda1-, and then added a SCSI hard drive - sdc1. The user then removed the USB memory card (sdb). Now, the SCSI hard drive is still named sdc, but if the SCSI is removed and then inserted, its name will change to sdb. Although there are other storage devices present, that IDE drive will still have an "a" in its name because it is the first IDE drive, and IDE device names are counted separately from SCSI, SATA, FireWire, and USB devices.

Restore using TestDisk:

Each recovery software has its own different functions, features and supported file systems. Here are some guidelines for using TestDisk to recover files on various file systems.

FAT16, FAT32, exFAT (FAT64), NTFS, and ext2/3/4:

TestDisk is an open source free software running under operating systems such as Linux, *BSD, SunOS, Mac OS X, DOS and Windows. TestDisk can also be installed by typing sudo apt-get install testdisk. TestDisk has many features, but this article will focus only on recovering files.

Use root privileges to open TestDisk from the terminal by typing the sudo testdisk command.

Now, the TestDisk command line application will be executed. The terminal's display will change. TestDisk asks the user if it can retain logs, this is entirely up to the user. If a user is restoring files from system storage, there is no need to keep logs. The available options are Generate, Append, and No Log. If a user wants to keep logs, the logs will be kept in the user's home directory.

怎样在 Linux 系统中恢复被删除文件

In the next screen, storage devices are listed in /dev/* format. For my system, the storage unit of the system is /dev/sda, which means my storage unit is a SATA hard drive (sd) and it is the first hard drive (a). The capacity of each storage unit is shown in Gigabytes. Use the up and down keys to select a storage device and click to enter.

怎样在 Linux 系统中恢复被删除文件

The next screen displays a list of partition tables (also called partition mapping tables). Just as files have file configuration tables, partitions have partition tables. A partition is a segmentation on a storage device. For example, in almost all Linux systems, there are at least two partition types - EXT3/4 and Swap. Each partition table will be briefly described below. TestDisk does not support all types of partitioned tables, so this is not a complete list.

怎样在 Linux 系统中恢复被删除文件

  • Intel - This type of partition table is very common in Windows systems and many Linux systems. It is also often called an MBR partition table.
  • EFI GPT - This type of partition table is commonly used in Linux systems. For Linux systems, this partition table is the most recommended because the concepts of logical partitions or extended partitions do not apply to GPT (GUID Partition Table) partition tables. This means that a Linux user can multi-boot from multiple types of Linux systems if there is one Linux system in each partition. There are of course other advantages to using a GPT partition table, but those are beyond the scope of this article.
  • Humax - The Humax partition map is for devices produced by the Korean company Humax.
  • Mac - Apple Partition Map (APM) for Apple devices.
  • None - Some devices do not have partition tables. For example, many Subor game consoles do not use a partition map. If a user attempts to recover files from such a device with other partition table types, the user will be confused as to why TestDisk cannot find any file systems or files.
  • Sun - Sun partition tables are available for Sun systems.
  • Xbox -Xbox is for storage devices that use the Xbox partition map.

If the user selects "Xbox", even though his system uses the GPT partition table, TestDisk will not be able to find any partitions or file systems. If TestDisk were to execute based on the user's selections, it might guess wrong. (The picture below shows the output when the partition table type is wrong)

怎样在 Linux 系统中恢复被删除文件

When the user has selected the correct option for their device, on the next screen, select the "Advanced" option.

怎样在 Linux 系统中恢复被删除文件

Now, the user will see a list of all file systems or partitions in the user's storage device. If the user selects the wrong partition map, in this step the user will know that they have made the wrong choice. If there are no errors, highlight the partition containing the deleted files by moving the text cursor. Use the left and right arrow keys to highlight the List located at the bottom of the terminal. Then, press Enter to confirm.

怎样在 Linux 系统中恢复被删除文件

A new screen will appear with a list of files and directories. Those white file names are files that have not been deleted, while red file names are those files that have been deleted. The rightmost column is the name of the file, the next column from right to left is the creation date of the file, and the left column is the size of the file (in bytes/bits), with "-" on the far left, " The columns "d", "r", "w" and "x" represent the permissions of the file. "d" indicates that the file is a directory, and other permission terms have little relevance to this article. The item represented by "." at the top of the list represents the current directory, and the item represented by ".." in the second line represents the superior directory of the current directory, so the user can reach the directory by selecting the line where the directory is located.

For example, I want to go into the "Xaiml_Dataset" directory, which basically consists of deleted files. By pressing the "c" key on the keyboard I will restore the file "computers.xaiml" and then I will be asked to choose a destination directory, of course I should place the file in another partition. Now, when I'm in my home directory, I press the "c" key. (When selecting the target directory) It does not matter which directory is highlighted. The current directory is the target directory, and a "Copy Complete" message will be displayed at the top of the screen. There will be a directory named "Xaiml_Dataset" in my home directory, which contains a Xaiml file. If I press "c" on more deleted files, the files will be placed in new folders without asking me for the destination directory.

When these steps are completed, press the "q" key repeatedly until you see the normal terminal appearance. The directory "Xaiml_Dataset" can only be accessed by the root user. To resolve this issue, use root privileges to change the permissions of this directory and its subdirectories. After doing this, the files are restored and the user can access them.

Special ReiserFS:

In order to restore a file from the ReiserFS file system, you first need to make a backup of all files in the partition. Because this method may cause file loss if certain errors occur. Then execute the following command, where DEVICE refers to the devices named in the form of sda2. Some files will be placed into the lost found directory while others will be saved to the location where they were originally deleted.

reiserfsck --rebuild-tree --scan-whole-partition /dev/DEVICE
Recover deleted files opened by a program:

Suppose the user accidentally deletes a file and the file is opened by a program. Although the file has been deleted from the hard disk, the program is using a copy of the file located in RAM. Fortunately, we have two simple solutions to recover the file.

If this software has a save function, such as a text editor, the user can resave the file, so that the text editor can write the file to the hard disk.

Suppose there is an MP3 file in the music player, and the music player cannot save the MP3 file. In this case, it will take more time to recover the file than before. Unfortunately, this approach is not guaranteed to work on all systems and applications. First, type the following command.

lsof -c smplayer | grep mp3

The above command will list all files used by smplayer. This list is searched for mp3 through the pipeline by the grep command. The input of the command is similar to the following:

smplayer  10037 collier  mp3    169r      8,1  676376  1704294 /usr/bin/smplayer

Now, type the following command to recover the file directly from RAM (/proc/ is mapped to RAM in Linux systems) and copy the file to the selected folder. Among them, cp refers to the copy command, the number 10037 in the output comes from the number of processes, the number 169 in the output refers to the file descriptor, "~/Music/" is the target directory, and the last "music.mp3" is the user's desired directory. The name of the recovered file.

cp /proc/10037/fd/169 ~/Music/music.mp3
Real deletion:

To ensure that a file cannot be recovered, you can use a command to "erase" the hard drive. Erasing a hard drive actually writes meaningless data to the hard drive. For example, many erasing programs write zeroes, random letters, or random data to the hard drive. No space is occupied or lost, the eraser simply overwrites the empty bits. If the storage unit is filled with files and there is no free space, all previously deleted files will disappear and cannot be recovered.

The purpose of erasing the hard drive is to ensure that private data is not visible to others. For example, a company may order some new computers and the general manager decides to sell the old computers. However, the new computer owner may see some of the company's confidential or customer information such as credit card numbers, addresses, etc. Fortunately, the company's computer technicians were able to wipe the hard drives before selling the old computers.

To install the erasure program secure-delete, type sudo apt-get install secure-delete. This command will install an assembly containing 4 programs to ensure that deleted files cannot be recovered.

  • srm - Permanently delete a file. Usage: srm -f ./secret_file.txt
  • sfill - Erases empty space. Usage: sfill -f /mount/point/of/partition
  • sswap - Erase swap space. Usage: sswap -f /dev/SWAP_DEVICE

If the computer actually clears those deleted files, it will take longer to perform the deletion task. Marking certain spaces as empty is quick and easy, but making the files disappear forever takes some time. For example, erasing a storage unit may take several hours (depending on the size of the disk). All in all, the current system works pretty well because even if the user empties the trash, they still have another chance to change their original mind (or mistake).


The above is the detailed content of How to recover deleted files in Linux system. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Linux就该这么学. If there is any infringement, please contact admin@php.cn delete
How to Create GUI Applications In Linux Using PyGObjectHow to Create GUI Applications In Linux Using PyGObjectMay 13, 2025 am 11:09 AM

Creating graphical user interface (GUI) applications is a fantastic way to bring your ideas to life and make your programs more user-friendly. PyGObject is a Python library that allows developers to create GUI applications on Linux desktops using the

How to Install LAMP Stack with PhpMyAdmin in Arch LinuxHow to Install LAMP Stack with PhpMyAdmin in Arch LinuxMay 13, 2025 am 11:01 AM

Arch Linux provides a flexible cutting-edge system environment and is a powerfully suited solution for developing web applications on small non-critical systems because is a completely open source and provides the latest up-to-date releases on kernel

How to Install LEMP (Nginx, PHP, MariaDB) on Arch LinuxHow to Install LEMP (Nginx, PHP, MariaDB) on Arch LinuxMay 13, 2025 am 10:43 AM

Due to its Rolling Release model which embraces cutting-edge software Arch Linux was not designed and developed to run as a server to provide reliable network services because it requires extra time for maintenance, constant upgrades, and sensible fi

12 Must-Have Linux Console [Terminal] File Managers12 Must-Have Linux Console [Terminal] File ManagersMay 13, 2025 am 10:14 AM

Linux console file managers can be very helpful in day-to-day tasks, when managing files on a local machine, or when connected to a remote one. The visual console representation of the directory helps us quickly perform file/folder operations and sav

qBittorrent: A Powerful Open-Source BitTorrent ClientqBittorrent: A Powerful Open-Source BitTorrent ClientMay 13, 2025 am 10:12 AM

qBittorrent is a popular open-source BitTorrent client that allows users to download and share files over the internet. The latest version, qBittorrent 5.0, was released recently and comes packed with new features and improvements. This article will

Setup Nginx Virtual Hosts, phpMyAdmin, and SSL on Arch LinuxSetup Nginx Virtual Hosts, phpMyAdmin, and SSL on Arch LinuxMay 13, 2025 am 10:03 AM

The previous Arch Linux LEMP article just covered basic stuff, from installing network services (Nginx, PHP, MySQL, and PhpMyAdmin) and configuring minimal security required for MySQL server and PhpMyadmin. This topic is strictly related to the forme

Zenity: Building GTK  Dialogs in Shell ScriptsZenity: Building GTK Dialogs in Shell ScriptsMay 13, 2025 am 09:38 AM

Zenity is a tool that allows you to create graphical dialog boxes in Linux using the command line. It uses GTK , a toolkit for creating graphical user interfaces (GUIs), making it easy to add visual elements to your scripts. Zenity can be extremely u

Top 22 Best Music Players for LinuxTop 22 Best Music Players for LinuxMay 13, 2025 am 09:25 AM

Some may describe it as their passion, while others may consider it a stress reliever or a part of their daily life. In every form, listening to music has become an inseparable part of our lives. Music plays different roles in our lives. Sometimes it

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools