Accidentally deleted an important file on Linux? Don't panic, but stop using the affected disk as soon as possible. The more data Linux writes to it, the greater the chance that your deleted files will be overwritten and become much harder or impossible to recover.
This guide walks you through the recovery process step by step, starting with the simple options like checking the Trash and file history, then moving to tools such as PhotoRec, extundelete, and ext4magic when deeper recovery is needed. You'll also learn how to identify the correct disk and filesystem, create a safe disk image before scanning, and handle LVM, LUKS, SSDs, and NVMe drives along the way. :contentReference[oaicite:0]{index=0}
Here are some of the advantages of following this recovery process:
- You stop the drive from overwriting the deleted data before you even start recovering anything.
- You get a clear order of operations instead of randomly trying tools and making things worse.
- You work off a forensic image first, so the original disk stays untouched no matter how many recovery attempts it takes.
- You cover journal based recovery (extundelete and ext4magic), raw signature scanning (PhotoRec), and the encrypted and LVM setups that trip most guides up.
- You walk away with an actual prevention setup instead of just fixing this one incident and repeating the mistake later.
- Works whether you're on Ubuntu, Debian, Rocky Linux, or RHEL, with the distro differences called out where they matter.
Prerequisites :
Operating System : Ubuntu 22.04/24.04, Debian 12, Rocky Linux 8/9, RHEL 8/9
Packages and Dependencies: testdisk (includes photorec), extundelete, ext4magic, ddrescue,
cryptsetup, lvm2, trash-cli
User Account : root user or a user account with sudo privileges
Recommended to run all administrative commands with sudo instead of logging in as root directly.
If you're not sure your account even has sudo rights yet, sort that out first, there's a walkthrough on how to configure sudo access in Linux that covers it in a few minutes.
Below is a checklist of things to do before starting:
- 1. Stop using the affected drive or partition for anything other than recovery work.
- 2. Check if the files were on a separate mount point (like
/home) so you can unmount just that, without rebooting the whole box. - 3. Figure out which filesystem you're dealing with, ext4 behaves very differently from btrfs or xfs when it comes to recovery, see this comparison of ext4, xfs, and btrfs if you're not certain.
- 4. Check whether the volume sits on LVM or behind LUKS encryption, both change which device path you actually need to point your tools at.
- 5. Have a second disk or USB drive ready, recovered files should never be written back to the same partition you're recovering from.
- 6. If this happened through a script or a bad Makefile target, don't rerun the script, that's a separate problem worth fixing once your data is safe.
If you're testing any of this on a fresh box before touching production data, it helps to know your way around the installer first, this Ubuntu 24.04 installation walkthrough is a decent starting point for a disposable test VM.
My Lab Setup :
Recovery Test Server: Operating System : Ubuntu 24.04 LTS Hostname : recovery-test IP Address : 192.168.1.50 Filesystem : ext4 (/dev/sdb1, mounted separately from root, no LVM or LUKS)
Step 1: Identify Exactly What You're Dealing With
Note:
Before running any tool, you need to know which device and filesystem actually held the deleted files, and whether LVM or LUKS sits between you and the raw partition. Guessing wrong here wastes time and, worse, risks you running a recovery scan against the wrong device while the real one keeps getting written to in the background.
Run this to see what's mounted where, and note the filesystem type in the third column.
LinuxTeck.com
/dev/sdb1 ext4 50G 12G 36G 25% /home
df only shows you what's currently mounted. Run this next to see the full device tree, including whether the partition sits directly on disk or behind LVM.
LinuxTeck.com
sdb
└─sdb1 ext4 /home
sdc
└─sdc1 LVM2_member
└─vg_data-lv_home ext4 /data
Note:
If lsblk shows a device type of LVM2_member, don't image the raw partition, that only gets you the LVM metadata, not the actual filesystem. Identify the logical volume first with sudo lvs, then every command later in this guide, dd, ddrescue, photorec, extundelete, ext4magic, should point at the mapped path, something like /dev/mapper/vg_data-lv_home, instead of /dev/sdc1.
Warning:
If the partition is a LUKS encrypted volume, none of the recovery tools in this guide can read it directly, they'll just see encrypted noise. Unlock it first with sudo cryptsetup luksOpen /dev/sdb1 recovery_volume, entering the passphrase when prompted. This creates a decrypted mapping at /dev/mapper/recovery_volume. From that point on, use /dev/mapper/recovery_volume wherever this guide references a device or partition, for df, lsblk, dd, ddrescue, photorec, extundelete, and ext4magic alike. If you don't have the passphrase, stop here, there's no recovery path around LUKS.
If the affected directory sits on the same partition as your root filesystem, remounting it read only isn't always practical without booting from a live USB. If that's your situation, don't run dd or ddrescue on the running system, boot into a live USB or ISO environment first, then jump to Step 4 and image the whole disk from there instead of working on a live root partition. The same applies if root itself is LVM or LUKS backed, unlock and identify the volume from the live environment before imaging anything.
Warning:
If this drive is an SSD or NVMe disk, check whether TRIM is enabled before getting your hopes up. TRIM (triggered by fstrim or the discard mount option) tells the drive to actually erase blocks the filesystem has marked as free, not just forget about them. If TRIM has already run since the deletion, the underlying data on those blocks is gone at the hardware level and none of the tools in this guide, PhotoRec, extundelete, or ext4magic, can bring it back. This limitation is specific to SSDs, a regular spinning hard drive doesn't have this problem.
Step 2: Check the Trash Directory First
Note:
If the files were deleted through a file manager like Nautilus or Dolphin, they very likely weren't actually removed, they were moved to a hidden Trash folder. Deletions from a terminal with rm skip this entirely, so this step only helps if a GUI was involved somewhere, but it costs nothing to rule out first.
List what's sitting in your local trash before assuming the worst.
LinuxTeck.com
drwxr-xr-x 2 devuser devuser 4096 Aug 29 10:12 .
drwxr-xr-x 4 devuser devuser 4096 Aug 29 10:12 ..
-rw-r--r-- 1 devuser devuser 8213 Aug 28 22:41 report_final.py
Tip:
If you find the file here, just copy it back with cp, don't rely on the "restore" button in every file manager, some of them are inconsistent about restoring the original folder structure.
Tip:
If the file was open in VS Code when it got deleted, check its local history before touching the disk at all. Open the file's folder in VS Code, right click the file in the explorer, or use the Timeline view in the sidebar, and look for Local History entries. VS Code keeps periodic snapshots of files you've edited independent of the filesystem, so this can recover a working copy in seconds with no disk-level tools involved.
Step 3: Install Your Recovery Toolkit
Note:
You'll want a few tools available before you touch the disk again. TestDisk and PhotoRec ship together in one package and handle partition recovery and raw signature scanning. extundelete and ext4magic both read the ext4 journal to recover original filenames, they overlap in purpose and it's worth having both installed since one occasionally succeeds where the other doesn't. ddrescue is a safer alternative to plain dd when the source disk shows any sign of failing, it skips bad sectors and retries them separately instead of stalling the whole copy.
On Ubuntu or Debian, install all of them in one go. Note that the ddrescue package is named gddrescue, even though the command itself is still ddrescue.
LinuxTeck.com
Building dependency tree... Done
The following NEW packages will be installed:
testdisk extundelete ext4magic gddrescue cryptsetup lvm2
Setting up testdisk (7.1-4build1) ...
Setting up extundelete (0.2.4-3) ...
Setting up ext4magic (0.3.2-4) ...
Setting up gddrescue (1.28-1) ...
On Rocky Linux or RHEL, EPEL covers testdisk, extundelete, ddrescue, cryptsetup, and lvm2, but not ext4magic, it isn't packaged for RHEL family distros and has to be compiled from source. Some EPEL packages, ddrescue included, pull in dependencies that live in the CodeReady Linux Builder repo (called PowerTools on older Rocky releases), which is disabled by default, so enable that before installing anything.
LinuxTeck.com
sudo dnf config-manager --set-enabled crb || sudo dnf config-manager --set-enabled powertools
sudo dnf makecache
sudo dnf install testdisk extundelete ddrescue cryptsetup lvm2 -y
testdisk-7.1-8.el9.x86_64
extundelete-0.2.4-9.el9.x86_64
ddrescue-1.28-2.el9.x86_64
cryptsetup-2.6.1-9.el9.x86_64
lvm2-2.03.21-4.el9.x86_64
Complete!
For ext4magic on Rocky or RHEL, install the build dependencies and compile it directly from the source tarball.
LinuxTeck.com
wget https://downloads.sourceforge.net/project/ext4magic/ext4magic/ext4magic-0.3.2/ext4magic-0.3.2.tar.gz
tar -xzf ext4magic-0.3.2.tar.gz
cd ext4magic-0.3.2
./configure CFLAGS="-O2 -Wno-error=implicit-function-declaration"
make
sudo make install
configuring ext4magic 0.3.2 ...
Making all in src
gcc -o ext4magic ...
Installed ext4magic to /usr/local/sbin/ext4magic
Note:
ext4magic installs to /usr/local/sbin by default, which isn't always in a regular login shell's PATH on RHEL family systems. If the command isn't found afterward, either call it with the full path, /usr/local/sbin/ext4magic, or switch users with su -l to pick up a root shell environment.
Here's how the tools in this toolkit differ, so you're not guessing which one to reach for first.
| Tool | Best For | Recovers Original Filenames | Works On |
|---|---|---|---|
| TestDisk | Rebuilding a wiped partition table or boot sector | Yes, if the filesystem structure is intact | Most filesystems |
| PhotoRec | Deep scan when the filesystem structure itself is damaged | No, generic names only | Any filesystem, file signature based |
| extundelete | Recently deleted files where the journal is still intact | Yes, reads the journal directly | ext3 and ext4 only |
| ext4magic | Same use case as extundelete, sometimes succeeds where it doesn't | Yes, reads the journal directly | ext3 and ext4 only |
| ddrescue | Imaging a disk that has bad sectors or is physically failing | Not applicable, it's an imaging tool, not a recovery tool | Any block device |
Step 4: Image the Drive Before You Run Anything Else
Note:
Do this before PhotoRec, extundelete, or ext4magic touch the disk, not after. Every recovery attempt writes something somewhere, even tools that claim to be read only can trigger filesystem checks or journal replays the moment they open the device. Cloning the raw device to an image file first means every scan below runs against a copy, so a bad attempt costs you nothing on the original. If the files were on your root partition, run this from a live USB or ISO environment, not from the running system. A live root filesystem keeps writing logs, temp files, and swap activity in the background the entire time dd is copying, and that makes the resulting image inconsistent even before you start recovering anything from it. If you unlocked a LUKS volume in Step 1, image the mapped device, /dev/mapper/recovery_volume, not the raw encrypted partition, that gives you a usable decrypted filesystem to scan. If the volume is on LVM, image the logical volume path instead of the raw partition for the same reason.
Note:
If you unlocked a LUKS volume or identified an LVM logical volume in Step 1, replace /dev/sdb1 in the dd and ddrescue commands below with your mapped path, for example /dev/mapper/recovery_volume or /dev/mapper/vg_data-lv_home. The commands as written assume a plain partition with no LUKS or LVM in the way, imaging the raw partition on a LUKS or LVM setup gets you encrypted noise or LVM metadata instead of your actual filesystem.
On a healthy disk, dd works fine.
LinuxTeck.com
records in: 1200+0
records out: 1200+0
If the drive is failing, showing SMART errors, or making unusual noise, use ddrescue instead. It works through the disk in passes, skipping unreadable sectors on the first pass and retrying them separately afterward, instead of stalling the entire copy the way dd can.
LinuxTeck.com
Press Ctrl-C to interrupt
ipos: 4831 MB, non-trimmed: 0 B, current rate: 78 MB/s
opos: 4831 MB, non-scraped: 0 B, average rate: 74 MB/s
non-tried: 0 B, bad-sector: 0 B, error rate: 0 B/s
rescued: 4831 MB, bad areas: 0, run time: 65s
pct rescued: 100.00%, read errors: 0, remaining time: 0s
time since last successful read: 0s
Finished
Tip:
Keep the logfile ddrescue creates, /mnt/backup/sdb1.logfile in the command above. If the copy gets interrupted, rerunning the exact same command resumes from where it left off instead of starting over, ddrescue reads its own logfile to know what's already been rescued.
Warning:
The output file, /mnt/backup/sdb1.img in the commands above, must live on a completely separate physical disk from /dev/sdb1, never on a different partition of the same drive. Writing the image back onto the same physical disk you're recovering from can overwrite the very blocks holding your deleted data, which defeats the entire point of imaging it first. Mount an external drive or a second internal disk at /mnt/backup before running this command, and confirm it's a different device with lsblk if you're not sure.
Tip:
Mount the image read only through a loop device to browse it safely without touching the original: sudo mount -o loop,ro /mnt/backup/sdb1.img /mnt/recovery. Note that this only works if you imaged a single partition, like /dev/sdb1 in the command above. If you imaged the whole physical disk instead, for example /dev/sdb, the image contains a full partition table rather than one filesystem, and a plain loop mount won't see any partitions inside it. In that case, map the partitions first with sudo losetup -P /dev/loop0 /mnt/backup/sdb.img, then mount the specific partition device it creates, such as sudo mount -o loop,ro /dev/loop0p1 /mnt/recovery.
Step 5: Scan the Image With PhotoRec When You Just Need the File Contents Back
Note:
PhotoRec ignores the filesystem's own bookkeeping entirely and scans raw blocks for known file signatures. That means it works even if the directory structure or inode table is badly damaged, but it also means recovered files come back with generic names like f0000123.py instead of their original filenames. Point it at the image file you created in Step 4, not the live device.
LinuxTeck.com
Image /mnt/backup/sdb1.img - 53 GB / 50 GiB
Partition Start End Size in sectors
1 P ext4 0 0 1 6527 99 63 104857600 [recovery]
Please select a destination to save the recovered files.
Warning:
Never save the recovered files back onto the same disk that holds the image or the original partition. PhotoRec will happily write into free space it hasn't scanned yet, which can overwrite the exact blocks holding the data you're trying to save. When it prompts for a destination, point it at a third location, a mounted USB drive or a separate internal disk, always.
Once files land in the recovery folder, sorting through hundreds of generically named files gets old fast. If you know roughly what you're looking for, the find command with a file type or size filter narrows things down quicker than scrolling through a file manager. If the filenames are generic but you don't know the type either, cd into the destination directory you gave PhotoRec, the recup_dir.1 folder referenced below sits directly inside it, and run the file command against everything there to sort by actual content type instead of guessing from extensions.
LinuxTeck.com
recup_dir.1/f0001102.txt: Python script, ASCII text executable
Step 6: Try extundelete or ext4magic for the Original Filenames
Note:
The ext4 journal keeps a short memory of recently deleted inodes, including their original names, as long as it hasn't wrapped around and overwritten that history yet. extundelete and ext4magic both read that journal directly, so when they work, you get your actual filenames back instead of PhotoRec's generic naming. Run them against the image file from Step 4, and note that both tools refuse to run against a mounted filesystem, so unmount first if you're pointing at a live device instead.
By default, extundelete writes recovered files into a folder called RECOVERED_FILES inside your current working directory, which is easy to miss if you forgot to cd into an external mount first. Change into your external drive and use --output-dir to be explicit about where files land.
LinuxTeck.com
sudo extundelete /mnt/backup/sdb1.img --restore-all --output-dir /mnt/external_disk/recovered
Loading journal descriptors ... 100%
42 recoverable inodes found.
Restored file "report_final.py" to directory /mnt/external_disk/recovered/
If extundelete comes up short, ext4magic is worth a shot on the same image, it uses a slightly different syntax but the same idea, point it at the image and give it a separate output location. Unlike extundelete, ext4magic won't create the output folder for you, so create it first with mkdir -p before running the recovery command.
LinuxTeck.com
sudo ext4magic /mnt/backup/sdb1.img -r -d /mnt/external_disk/recovered
Loading journal ... done
Deleted inodes found: 37
Recovering to /mnt/external_disk/recovered ...
report_final.py recovered successfully
Whether the file even shows up in either tool comes down to what actually happens when Linux runs rm, the man page for it explains the underlying unlink behavior if you want the full picture of why this isn't always recoverable.
Building a Safety Net So You Don't Need to Recover Deleted Files in Linux Again
Once your files are back, it's worth spending twenty minutes making sure you're not back here next month. A few small habits cover most of the ways people lose data on Linux.
If you're setting up a new system or rebuilding one after this, consider btrfs or ZFS with scheduled snapshots instead of ext4. A snapshot taken every hour or so means an accidental delete is just a rollback away, no PhotoRec, no journal scanning, no imaging a drive at 2am. It's more setup work upfront than a plain ext4 install, but for anything you'd genuinely miss, it's worth it.
Install trash-cli so terminal deletions land in a recoverable trash folder instead of vanishing immediately, and get comfortable typing trash instead of rm out of habit. For anything code related, commit early and often, a git history is a far better safety net than any recovery tool. For everything else, an actual backup schedule beats hoping recovery works when you need it. A simple automated backup script paired with a scheduled job covers most home and small server setups, and if cron feels clunky for that, systemd timers are a cleaner way to run it reliably. For anything running production workloads, look into proper server backup solutions rather than relying on manual copies you'll eventually forget to run.
If your data actually lives on a remote server rather than your own machine, a good chunk of this pain goes away simply by picking hosting that handles snapshots and backups for you. When people ask me what to look at for that, I usually point them toward this Cloudways review, it's a decent rundown of whether managed hosting is worth it if you're tired of babysitting backups yourself, and it pairs well with the general advice in this Linux VPS hosting comparison if you're still shopping around.
Conclusion:
Recovery isn't guaranteed, but identifying the real device layout, encrypted or LVM or plain, imaging it first, and then working through trash, PhotoRec, extundelete, and ext4magic against that copy gives you the best realistic shot to recover deleted files in Linux without risking the original. Once you're through this, put trash-cli, snapshots, and a real backup schedule in place so the next accidental deletion is a non event instead of a panic. Drop me your feedback/comments. Feel free to share this article with others if you like it.
Questions I Get Asked About This All the Time
I already rebooted after deleting the files, is everything lost now?
Not necessarily. A reboot alone doesn't overwrite your data, it's continued disk activity that does the damage. If you haven't been writing new files since the reboot, image the drive now and run PhotoRec or extundelete against the copy rather than waiting any longer.
Does this work the same way on an SSD as it does on a spinning hard drive?
Not really. SSDs use TRIM, which tells the drive to actually erase blocks marked as deleted instead of just leaving them alone. If TRIM has already run on that partition, the underlying data is often gone for good at the hardware level, no tool in this guide can pull it back. HDDs don't have this problem, deleted data usually just sits there until something else overwrites it.
My drive is LUKS encrypted, does any of this still work?
Yes, but only if you have the passphrase. Unlock the volume first with cryptsetup luksOpen, then run everything in this guide against the decrypted mapper device it creates instead of the raw partition. Without the passphrase, the tools here can't do anything, the recovery tools have no way around the encryption itself.
My data was on an LVM logical volume, do the same commands apply?
Mostly yes, just swap the device path. Use lsblk -f and lvs to find the actual logical volume, something like /dev/mapper/vg_data-lv_home, and point dd, ddrescue, photorec, extundelete, or ext4magic at that instead of the raw partition. Imaging the raw partition on an LVM setup only captures LVM metadata, not your filesystem.
I emptied the trash folder too, is that different from a normal delete?
Emptying trash is functionally the same as an rm delete, the files are unlinked from the filesystem but the actual data usually still sits on disk until it's overwritten. Treat it exactly the same way, image the drive and run PhotoRec or extundelete.
Why did PhotoRec recover my files with weird names instead of the originals?
That's just how PhotoRec works, it scans for file signatures in raw disk blocks and has no access to the filesystem's naming information. If you need the original filenames back, extundelete or ext4magic are more likely to preserve them since they read the ext4 journal directly, but that only works if the journal entry hasn't been overwritten yet.
Do I really need to image the drive, or can I just run these tools directly on the live disk?
You can technically run PhotoRec directly on a mounted or live device, but it's risky since the system keeps writing to that disk in the background, logs, swap, temp files, all of it competes with your recovery. Imaging first with dd or ddrescue and working off the copy means a mistake costs you nothing on the original.
To recover deleted files in Linux, should I use TestDisk or PhotoRec first?
If your partition table or boot sector got wiped, start with TestDisk, that's what it's built to rebuild. If individual files are missing but the partition itself mounts fine, go straight to PhotoRec, extundelete, or ext4magic, running TestDisk first won't add anything in that case.
From your first terminal command to advanced sysadmin skills — every guide here is written in plain English with real examples you can run right now.
