blog-banner

Restoring Removed Files (rm -rf) in Linux with TestDisk

  • LINUX SERVER
  • Ubuntu

There are odd times when we would have accidentally deleted some important folders without having any actual backup. It happened to us, that 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 a 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 as 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 process to figure out 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 the word “knackforge” and move them 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 versions of the same file, at that time you can decide based on file number, say f123456.php is a newer one than f123454.php

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

Get awesome tech content in your inbox