I overwrote a large file with a blank one on a linux server. Can I recover the existing file?

I came back to my machine, tried saving a file over ssh onto my linux server (CentOS).

It failed.

I wasn't interested in keeping any changes I had made so I closed my editor and reopened the file (over ssh).

The save attempt wiped the file.

I have made loads of changes to it since I last uploaded to revision control.

Seeing as it has just wiped the file I assume the data is still there. It's just a text file (php), is there any way of recovering it?


Solution 1:

Seeing as it has just wiped the file I assume the data is still there.

I'm afraid you assume incorrectly. Depending on the filesystem and underlying device, the bytes that once made up the file might still live on disk, but it's going to be inaccessible to anything short of full-on forensic recovery, which I'm certain you don't want to pay for.

Have you checked your temp directory to make sure you don't have another copy laying around? Because you're probably not going to get that particular file back.

Sorry for the bad news.

Solution 2:

If the inode was dereferenced, you might be able to recover the data. If the blocks were overwritten, it will require forensics recovery like Matt identified.

My preferred method is to use debugfs, which can be used to access inodes that have been dereferenced by not yet overwritten. The lsdel command is key. With some simple scripts, you can create hardlinks to all inodes output by lsdel and start groking the data.

There's also other tricks, such as grepping the filesystem or finding the inode using a different method.

Good luck and be careful. Low level utilities can easily produce disastrous results without caution.

Solution 3:

Use PhotoRec. There you go. Had a problem once (Linux) where I deleted a partition that was being used as a Physical Volume in an LVM2 Volume Group, and did not have a backup of the /etc/lvm/backup file. PhotoRec solved it neatly, going over the deleted partition and recovering this file (a plain text file) for me, from where I was able to reconstruct the original configuration. Best of luck.