Site icon NetworkHunt

How to Recover Deleted Files in Linux

recover deleted files in linux

Recovering deleted files in Linux is possible as When you delete a file, it isn’t immediately removed from your system. The file’s data stays on the disk until new data overwrites it. So, acting quickly increases your chances of recovery.

Table of content

To Recover Deleted Files in Linux using lsof command

1. Unmount the Drive (Stop Using It Immediately)

When you realize you’ve deleted an important file, unmount the drive to prevent overwriting.

2. Use the lsof Command

Sometimes, if a deleted file is still open in a running application, it can be recovered with the “lsof” command.

We have divided this into three steps-

1. We will create a new file
2. Then we will delete the newly created file.
3. And in last we will recover the deleted files in Linux.

1. Create a test file to try this method:

    touch /tmp/testf
    tail -f /tmp/testf &
    ps -ef | grep tail

    2. Delete the file:

    rm /tmp/test

    3. Now the file is deleted, let’s try to recover it.

    1. Use lsof to find the file:
    $lsof | grep -i test
    Look for the PID of the process holding the file.

    2. Copy the file back to its original location:

      cp /proc/<PID>/fd/<FD> /tmp/
      mv /tmp/<FD> /tmp/test

      -: Recovering of file is done.

      Use Foremost (A Forensic Recovery Tool) to recover deleted files in Linux.

      Foremost is a tool to recover deleted files like images, videos, and documents from storage devices like hard disk, memory card, pendrives etc.

      How to Use Foremost: To use Foremost tool, we need to install it first in the machine.

      1. Install Foremost (if not already installed):
        sudo apt install foremost
        2. Run Foremost to recover the deleted files in Linux:
        sudo foremost -v -q -t png -i /dev/sda1 -o ~/recovered_files

        Note: Don’t recover files on the same drive where they were deleted, as it may overwrite data.

        Recovering deleted files in Linux is possible if you act quickly before the data is overwritten. By unmounting the drive, using the lsof command to retrieve files still in use, or utilizing forensic recovery tools like Foremost, you can increase your chances of restoring lost data. Each method is useful depending on the scenario—lsof works for files still held by running processes, while Foremost is effective for deep recovery of deleted files from storage devices. To prevent data loss, consider regular backups and using file recovery tools as soon as you realize a file is deleted.

        Exit mobile version