How to Recover a Deleted File in Linux
Whenever we delete something from our system, it does not actually get deleted, till that space gets overwritten by something else in the disk. You can also read about how to securely delete any files permanently.
The best way to Recover a Deleted File in Linux is as follows:
Unmounting a device immediately after we realize we’ve deleted important files is the best option to prevent the data blocks of the deleted files from being overwritten with other data.
- At 1st Shut down the system, and do the recovery process by booting from a Live CD/USB
- Search the partition that contains the file you deleted, for example- /dev/sda1
- Recover the file (make sure you have enough space)
2. lsof command:
Sometimes an open file is deleted accidentally, in that case, lsof command is a life-saving command to recover that file.
Step 1: Make a test file inside the /tmp directory
Step 2: Run something that will hold the file open:
tail -f /tmp/test &
Note: Here the number is 8561 but in your case, it might be different so use the commands accordingly.
Step 3: List the process for confirming the open process
ps -ef | grep 8561 | grep -v grep
$ rm /tmp/test $ ls -l /tmp/test
So now we are sure that the file is actually deleted, lets now try to recover it with the help of lsof command
Step 5: For displaying the open file descriptor of the process use lsof command
$lsof | grep -i test
The PID of the process that is holding that file open is displayed in the second column.
Step 6: Now we have to locate the open file descriptor in /proc directory
$ls -l /proc/8561/fd/3
Step 7: Now the open file (that was deleted but opened by some other process) can be copied back to its original location i.e., under /tmp. After that, you can also rename it by its original name
$ cp /proc/8561/fd/3 /tmp/ $mv /tmp/3 /tmp/test $ ls -l /tmp/test
3. Foremost (forensics tool):
Foremost is a forensic tool that comes more or less pre-installed in kali Linux but if it is not there, you can install it from the command line. The foremost tool is used to recover deleted files from hard disk, memory card, pen drive, etc.
This tool uses a process called File Carving for recovering data.
For recovering a deleted image use the following command:
sudo foremost -v -q -t png -i /dev/sda1 -o ~/test
Where /dev/sda1 is the underlying partition where /boot resides.
where /home/tithi/Downloads/gg is a directory on a separate disk where the recovered file will be located(don’t recover the files on the same drive where the removed ones were located, it might fail to recover anything). A lot of files will be get recovered together and the recovered name file won’t be similar to the original one.