Skip to main content
Restoring Removed Files Linux TestDisk

Restoring removed files (rm -rf) in Linux with TestDisk

There are odd times where we would have accidentally deleted some important folders without having any actual backup. It happened to us, one of our team members on the way to remove a symbolic link, accidentally deleted a web folder using rm -rf, though we normally maintain GIT repo, for this temporary project, we did not. So we had to restore it though initially, it looked gloomy. I stumbled upon "extundelete" but that could not restore any important files. Then we tried http://www.cgsecurity.org/wiki/TestDisk. See more details below

In Ubuntu/Debian based system, you can install using

apt-get install testdisk

Let's say you lost the folder in /home/username/webroot, then we can try restoring the whole volume. I tried to restore all file types, so used

photorec /debug /log /d /mnt/recover/disk /cmd /dev/xvdf1 partition_none,options,mode_ext2,fileopt,everything,enable,search

/dev/xvdf1 is the actual volume that has /home/username data. You can find that using the fdisk command.

/mnt/recover/disk is the path where files will be restored

See http://www.cgsecurity.org/wiki/Scripted_run for more details. You will only get the content of the file, not the file names. So we need to run another processing to figure the important files.

Moving files

Then I wanted to move all PHP files from the restored folder to all PHP folder,

find ./testdisk.* -name \*.php -exec cp {} allPHP \;

Note, I got many folders in an incrementally numbered fashion on testdisk restoring. 

Then I wanted to find all PHP files with a word “knackforge” and move to a new folder.

grep -rn --include \*.php “knackforge” /home/ubuntu/allPHP/ | awk -F ':' '{print $1}' | xargs -I '{}' cp ‘{}’ knackforge_php/

You can apply this to your criteria. You may get multiple version of the same file, at that time you can decide based on file number, say f123456.php is newer one than f123454.php

Before you process the files, you can try running fdupes to remove duplicate files.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.