TL;DR: Use parted rescue
The Problem
Last Sunday evening, I accidentally deleted the partitions of my laptop while it was running. Initially, I wanted to remove all partitions from an SD card and create a single partition spanning the whole card. Absent-mindedly I went
... sudo parted /dev/sda ... rm 1 ... rm 2 ... rm 3 ...
... mkpart ... 0% ... 100% ... quit ...
Done.
Later that evening, when I restarted the computer, I realized what I did.
/dev/sda
was the internal disk of my laptop. I hadn’t even thought about which
device the SD card was. The correct device would have been /dev/mmcblk0
. Maybe
tab-completion was doing its part: I probably did sudo parted /dev/sd<TAB><TAB>
to see which disks
are there, but it automatically completed it to sda
after the first <TAB>
.
Ok, I’ve screwed up. How to fix this? Luckily, I didn’t format the new
partition. I wanted to let my digital camera do the job. (How should I know what
file system it needs: fat? fat32? exfat? ntfs?) However, not formating the new
partition is key here. During my self-destruct
parted
-session, I deleted the partitions from the partition table. But still, it should
have left the rest of the disk untouched, including the actual contents of the
partitions, the file systems, and all my data. Theoretically, I only need to
recreate the same partitions with the exact same sizes, and everything should
be back to normal (without using a backup).
The Solution
parted
was my enemy here, but as it turns out, parted
is also your best
friend when you want to restore deleted partitions.
When you boot a live Linux system from a USB stick, you can operate on the fried disk with parted.
The task is to recreate the same partitions. Well, I didn’t remember the exact sizes and positions of my partitions. (Should I keep a copy of my partition table in my wallet since I don’t like to pay attention when I work with parted?)
You could try to at least match the beginning of the partitions and ask the contained file system how
large it is. However, there is a much easier way. parted
ships with the rescue
command. The rescue command asks for rough limits were the beginning of a
partition was and scans the space for magic blocks and file system headers. When
it finds something, it directly asks whether it should recreate the previous partitions. See
https://www.gnu.org/software/parted/manual/html_node/rescue.html.
Within 2 minutes, everything was back to normal.
This might also interest you