Have you ever made a mistake on Linux that left you scrambling to recover critical files? Recently, I did just that while working on a project. This article details my experience and the solution that saved me—so you’re prepared if disaster strikes.
The Mistake: A Simple Command Gone Wrong
While testing how to build a Windows version of a logging agent with mingw
, I ran this command in the terminal:
$ rm * .exe
I intended to delete only .exe
files, but the misplaced space caused all files in the directory to be deleted, including several .c
files representing days of work. Without backups, I faced the real possibility of losing a week of effort. If you’ve ever been in a similar situation, you know how disheartening this can be.
Initial Attempts: Tools That Didn’t Work
Desperate to recover my files, I searched online for solutions to recover deleted files on Linux. I came across several tools, including:
- extundelete:
extundelete --restore-all
- ext4magic:
ext4magic /dev/vda1 -f root/log-export
- testdisk
Despite following detailed guides, none of these tools worked in my case. It seemed my files were lost—until I discovered PhotoRec.
The Solution: PhotoRec to the Rescue
PhotoRec, an open-source data recovery tool, turned out to be the hero of the day. Here’s how I used it:
- Install PhotoRec:bashCopy code
$ sudo apt install photorec
- Run PhotoRec:bashCopy code
$ photorec
- Select the Partition: Follow the on-screen instructions to choose the correct disk partition.
- Accept Defaults and Recover Files: PhotoRec scanned the unused sectors of my disk and recovered file headers of various types. After about 15 minutes, it saved nearly 100GB of recovered files to the directory I specified.
Sorting Through Recovered Files
The recovered files were organized into directories like /root/recover/recup_dir.*
. To locate specific files, I used grep
to search for unique identifiers in my code. For instance, searching for #ifdef WIN32
helped me identify my C files:
$ grep -r "#ifdef WIN32" /root/recover/
Similarly, I searched for specific debug statements or keywords unique to my project, such as:
$ grep -r "DEBUG: f should never reach here" /root/recover/
When multiple versions of a file were recovered, I used ls -la
to compare file sizes and timestamps, selecting the most recent or largest version.
Lessons Learned
- Always Double-Check Commands: A single misplaced space in
rm
can cause catastrophic data loss. - Back Up Regularly: Automated backups can save hours of recovery work.
- Use PhotoRec: If all else fails, this open-source tool is a lifesaver for recovering lost files.
Mistakes happen, but with tools like PhotoRec, they don’t have to spell disaster. Whether you’ve accidentally deleted files or simply want to prepare for potential mishaps, PhotoRec is worth having in your toolkit.