I deleted a partition
Writes to the disk: yes, the partition table, at the very end and only when you say so. Your files are usually still there: deleting a partition removes its entry in the table, not the data.
Do not create new partitions, format, or install anything on that disk. That is what really destroys the data.
1. Work on a copy, if you can
sudo ddrescue /dev/sdX /mnt/target/disk.img /mnt/target/disk.map
Repair the copy, confirm your files are there, and only then repeat on the real disk. If you have nowhere to copy it, you can run TestDisk on the disk directly, as it writes only at the end.
2. Find it with TestDisk
cd /mnt/target # it leaves testdisk.log here
sudo testdisk /log disk.img # or /dev/sdX
-
Choose the disk, and Proceed.
-
Choose the partition table type yourself.
On a GPT disk left with no partitions, TestDisk proposes Intel. Choosing that would replace your GPT with an MBR. Choose EFI GPT. If you are not sure which the disk had,
sudo gdisk -l /dev/sdXsays whether a GPT is present. -
Analyse, then Quick Search.
-
Your partition appears in the list. Press P to list its files. If you see them, you have the right one. Press q to go back.
-
With the arrows ← →, change its status: on GPT, from
D(deleted) toP(primary); on MBR,*(bootable) orP. Then Enter. -
Write, then Y to confirm. Nothing has been written before this.
-
Leave with Quit, and reboot if you repaired the real disk.
If Quick Search does not find it, try Deeper Search.
3. Check it
On an image:
sudo losetup -Pf --show disk.img # prints /dev/loopN
sudo mount -o ro,noload /dev/loopNp1 /mnt/check
On the real disk, after rebooting:
sudo mount -o ro,noload /dev/sdXn /mnt/check
noload is for ext4; for XFS use norecovery, and for others simply ro.
If it was formatted, or TestDisk finds nothing
The partition’s file system is gone or overwritten. photorec recovers files by their contents, without their names or folders, to another disk.
Tested in a virtual machine, through TestDisk’s menus, on copies of a GPT disk and an MBR disk, each with an ext4 partition deleted: the partition came back with its files identical. Not tested: NTFS, or partitions overlapping others.