Helping a Friend Save the Day with TestDisk [EN/ES]
Tools: testdisk · photorec · DMDE · ddrescue — Boot media: Linux Mint 21
Because of my background as a computer engineer, every tech problem in my world—however small or complex—lands on my desk. My academic department, devoted to social sciences, is full of people well into their careers or, generally speaking, not exactly at home with technology. Last Thursday I got a call from a professor I think very highly of because he was pivotal to my doctoral training, completely thrown by one of those classic "wrong click" disasters. I talk about a well-respected Doctor of Philosophical Sciences here in Cuba, distinguished in the field of STS Studies, with more than forty years of teaching and research behind him. He'd plugged in a USB drive, and when it threw an error, he decided to format it. That alone was a rash call, as I told him—but he made the decision and went through with it. The problem was that, without realizing it, he ended up formatting the HDD holding all of his persistent data: his entire body of work and his scientific library.
Versión en español — el contexto
Dada mi formación de base como ingeniero informático, todos los problemas de este ámbito que se dan en mi entorno laboral, plagado de gente muy buena pero no versada en tecnología, terminan cayendo sobre mí. El pasado jueves recibí la llamada de un profesor que estimo mucho —crítico en mi proceso de formación doctoral— totalmente desconcertado por uno de esos famosos "dedos mal metidos" en la computadora. Les hablo de un doctor en ciencias filosóficas muy reputado acá en Cuba —con distinción en el área de los estudios sociales sobre ciencia y tecnología—, con más de cuarenta años de trabajo en la formación y la investigación. Este amigo insertó un dispositivo USB, y ante un fallo que este presentó, decidió formatearlo. Ya esto era una decisión apresurada, como le comenté, pero el hecho es que la tomó y la ejecutó. El problema es que, sin percatarse, terminó formateando el HDD donde tenía todos sus datos persistentes, con todo su historial de trabajo propio y su biblioteca científica.
Since I'm fairly fresh in his memory and we've built a good relationship, he chose to hand me the delicate mission of recovering his files. Fortunately, even though I've spent the last several years much more immersed in the social sciences than in pure computing, I've never let my basic skills go to waste. Working consistently with GNU/Linux distributions helps a lot there, and using the terminal regularly helps as well. It had been years since I'd last recovered a partition after a quick format, but I remembered well what cgsecurity's testdisk—which bundles photorec— could do for this particular headache.
Versión en español
Como me tiene muy presente en la memoria y, además, hemos establecido una relación muy positiva, de todas las opciones que valoró optó por asignarme a mí la sensible misión de recuperar su información. Afortunadamente, aunque en los últimos años he estado mucho más metido en el dominio de la ciencia social que en el de la informática pura, nunca he descuidado el mantenimiento de mis habilidades básicas. En eso me ayuda mucho trabajar siempre con distribuciones del sistema operativo GNU/Linux y, en esta línea, usar con regularidad la consola. Llevaba años sin recuperar una partición de un disco tras un formateo rápido, pero recordaba bien las posibilidades de la herramienta testdisk—que integra photorec— para tratar este particular dolor de cabeza.
cluster map · disk untouched ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 06% assessed
As always, my first piece of advice to my colleague and friend was to shut down his laptop immediately to stop any silent write traffic to the compromised partition, since that cuts down the odds of recovery. Because this was, fortunately, a quick format, we were looking at the least catastrophic scenario: most of the data survives even though the used space shows up as zero. Generally, all that gets erased is the reference to that data— the file table with the metadata.
Versión en español — apagar el equipo
Como siempre, la primera recomendación al colega y amigo fue apagar de inmediato su laptop para evitar todo tráfico de escritura silencioso en la partición comprometida, lo que reduce las posibilidades de recuperación. Dado que se trató, afortunadamente, de un formateo rápido, estábamos ante el escenario menos catastrófico, porque la mayoría de los datos se mantienen aunque visualmente el espacio utilizado aparezca en cero. Por lo general, solo se borran las referencias a esos datos: la tabla de archivos con los metadatos.
So I put together a live USB with Linux Mint 21 and told him he could come by my university to run the tool. The process took a while, because the professor had no real grasp of his own storage setup, and what I was reading after typing lsblk in the command line didn't line up with the usual picture of one disk with two partitions: one for the OS, up to 100 GB, and a bigger one for persistent data that's fairly immune to any operating-system meltdown.
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 931.5G 0 disk
├─sda1 8:1 0 931.4G 0 part
sdb 8:16 1 232.9G 0 disk
├─sdb1 8:17 1 1G 0 part /boot/efi
└─sdb2 8:18 1 231.9G 0 part /
It turned out the professor had a 250 GB solid-state drive for the OS—which Mint mounted as /dev/sdb— and a 1 TB HDD where the formatted partition actually lived.
Versión en español — el USB de arranque
Preparé un live USB con Linux Mint 21 y le dije que podía pasar por la universidad para ejecutar la herramienta. El proceso fue largo porque el profesor no tenía dominio de las características de su infraestructura de almacenamiento, y lo que yo leía tras teclear el comando
lsblkno tenía mucho sentido con la idea estándar de un solo disco con dos particiones: una para el sistema operativo, de hasta 100 GB, y una segunda, más grande, para los datos persistentes, bastante inmune a cualquier quiebre del sistema operativo. Al final, el profesor tenía un disco de estado sólido de unos 250 GB para el sistema operativo —que Mint cargó en/dev/sdb— y un HDD de 1 TB con la partición formateada.
Not knowing the size of his own HDD had some effect on how we could operate relative to the plan I'd laid out, since he hadn't brought an external drive with enough room to work "clean"—by first imaging the disk with something like ddrescue:
$ ddrescue -d /dev/sda /mnt/backup/sda.img /mnt/backup/sda.log
# image the failing disk first, then recover from the image —
# skipped here for lack of a big enough external drive
Still, that wasn't a dealbreaker. I went ahead and ran ./testdisk against /dev/sda directly.
Versión en español
El hecho de que él desconociera el tamaño de su HDD tuvo cierto impacto en nuestra capacidad operativa respecto al plan que me había trazado, porque no trajo un disco externo con suficiente espacio para trabajar "en limpio", como siempre se recomienda, creando primero una imagen con ddrescue, por ejemplo. Pero bueno, esto no era algo insalvable, y terminé corriendo ./testdisk contra /dev/sda.
cluster map · scan running █████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 18% assessed
That took about five hours to finish, and my mistake—after years away from testdisk's interface or unaware of its current distribution—was not listing the partitions with p as the tool found them. I figured I should wait for the whole process to finish, but by the time it did, the tool had dropped me on a screen that only told me certain partitions couldn't be recovered, with no way left even to try listing with p.
Versión en español — el error de no listar a tiempo
Esto tomó unas cinco horas en completarse, y el problema, de mi parte —tras años sin "chocar" con testdisk—, fue no listar con
plas particiones que la herramienta iba detectando. Mi idea era esperar a que el proceso terminara, pero, llegado ese momento, el sistema me llevó a una pantalla que solo indicaba que ciertas particiones no podían ser recuperadas, y donde ya ni siquiera podía intentar listar con "p".
cluster map · dead end reached █████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 11% assessed
Rattled by that, I turned to ChatGPT, and its suggestion was to abandon testdisk altogether and switch to DMDE—which, in its free version, has its limits. But something saved me: its other suggestion, to back out of testdisk gradually, pressing q on each screen instead of quitting outright.
# instead of force-quitting from the dead-end screen:
q → back one screen
q → back another
q → ...until the partition list reappears
p → list files in the selected partition
Sure enough, once I got back to the screen listing every partition it had found, I tried listing there and found, thankfully, the entry holding the professor's historical files—which we copied onto two external HDDs he'd brought along.
Versión en español — ChatGPT, DMDE, salir con "q"
Turbado con esto, consulté a ChatGPT, y su sugerencia fue abandonar la ruta de testdisk y apelar a DMDE, que, en cualquier caso, tiene sus limitaciones en la versión gratuita. Pero algo me salvó: su otra sugerencia de salir poco a poco de testdisk, con "q" en cada pantalla. Entonces, cuando retorné a la pantalla donde tenía listadas todas las particiones, intenté listar de nuevo y encontré, afortunadamente, la entrada con los archivos históricos del profesor, que copiamos a dos HDD externos que él había traído.
cluster map · archive located ███████████████████████████████░░░░░ 82% assessed
That part didn't go quite as smoothly as we'd have liked: one drive didn't have enough space, and the other had painfully slow, unreliable read/write behavior. Either way, the professor "came back to life."
Versión en español — la copia a los discos externos
Esta fase no fue tan ideal como hubiéramos querido, porque uno de los discos no tenía espacio suficiente y el segundo tenía un funcionamiento harto tortuoso, con problemas de lectura y escritura. En cualquier caso, el profesor "volvió a la vida".
A few things are still left to check and sort out—like why, according to what he remembers, certain files that should have been recovered aren't showing up in the right folders. I explained that as long as he doesn't write anything new to the disk, we can always run ./testdisk again—or DMDE—and photorec as a last resort (it's bundled with testdisk anyway), with the same odds we had yesterday. Otherwise, he'll need to find an HDD bigger than 1 TB to image the drive and have something to work with anytime later, since he lives far from my university and transportation in Cuba is seriously complicated these days.
Versión en español — lo que queda pendiente
Nos quedaron algunas cosas por revisar y perfilar —como la duda de por qué, según lo que él recuerda, ciertos archivos que debían haberse recuperado no aparecen en las carpetas correspondientes—, pero le expliqué que, mientras no vuelva a escribir en el disco, podemos volver a correr testdisk o DMDE y, en última opción, photorec —integrado al propio testdisk—, con las mismas posibilidades que teníamos ayer. De lo contrario, deberá conseguir un HDD de más de 1 TB para grabar una imagen y trabajar sobre ella en cualquier momento posterior, porque vive lejos de mi universidad y el transporte está sumamente complicado en Cuba.
cluster map · session closed ██████████████████████████████████████ 90% assessed
So far I'm satisfied—and he's happier than anyone—to have been able to help my friend out, which, as a side effect, gave my old technical skills a bit of much-needed maintenance.
Versión en español
Me siento satisfecho de haber podido contribuir con este amigo, lo que, de paso, me llevó a darle mantenimiento a viejas habilidades técnicas.
Tools referenced: testdisk / photorec (cgsecurity) · DMDE · ddrescue · Linux Mint 21
Source for the GPT-generatedcover image.
Leave Helping a Friend Save the Day with TestDisk [EN/ES] to:
Read more #hive-196387 posts
Best Posts From Juan Manuel
We have not curated any of limonta's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Juan Manuel
- Helping a Friend Save the Day with TestDisk [EN/ES]
- A proactive cache system for my CACR tracker
- The Latin American Report: Why Did Cuba End Up Alone?
- Los White Sox están hablando en serio [ES/EN]
- Building a Better Way to Navigate the Cuban Assets Control Regulations
- Three Tunes "Tuesday": Take Cover! [ES/EN]
- Counterfactuals vs. Material Conditions: What Makes an Economic Model Scientifically Useful?
- Finding Cuba-Related Records with the ForeignAssistance.gov API
- I earned my PhD! [EN/ES]
- A New, LLM-Assisted Pipeline to Back My Research