Contents

How to Recover Deleted Files on Linux from ext4 and Btrfs

If you just ran rm on something important and you are reading this in a panic - stop what you are doing on that filesystem right now. Run mount -o remount,ro /dev/sdX to remount the partition read-only before anything else. Every write operation that hits the disk after deletion reduces your chances of getting those files back. With that out of the way, here is a direct answer: for ext4, use extundelete or debugfs as your first recovery attempt, and PhotoRec as a fallback. For Btrfs, roll back a snapshot if you have one, or use btrfs restore if you do not. The details matter quite a bit depending on your situation, so read on.

Why Recovering Deleted Files on Linux Is Harder Than You Expect

Most Linux users learn the hard way that rm is permanent. Unlike Windows with its Recycle Bin or macOS with the Trash, the terminal rm command removes the directory entry pointing to the file’s inode and marks those data blocks as free. The actual bytes remain on disk until something else overwrites them - but that overwrite can happen seconds or hours later depending on your hardware and system activity.

On an actively used system, journal writes, log rotation, package manager operations, and browser cache activity constantly allocate new blocks. The window you have before deleted data gets overwritten shrinks with every running process that touches the disk.

SSDs make this significantly worse. Modern Linux distributions enable fstrim.timer by default, which runs weekly TRIM operations. Some mount options include discard for continuous TRIM. Once the SSD controller receives a TRIM command for those blocks, it may zero or remap them at the hardware level - no software recovery tool can bring that data back. You can check if your drive supports TRIM with:

cat /sys/block/sda/queue/discard_max_bytes

If the value is non-zero, TRIM is supported and may already be active.

Filesystem type also determines which tools work and how likely recovery is:

FilesystemRecovery DifficultyTool SupportNotes
ext4ModerateGood - extundelete, debugfs, PhotoRecJournal retains metadata; best-supported recovery
BtrfsEasy with snapshots, hard withoutbtrfs restore, snapshotsCOW architecture complicates traditional undelete
XFSVery hardAlmost nonexfs_undelete is experimental; PhotoRec is your only real option
ZFSEasy with snapshotszfs rollback, zfs diffSimilar to Btrfs - snapshots are the primary recovery path

The golden rule: stop writing to the filesystem immediately. If the deleted files were on a non-root partition, unmount it. If they were on the root filesystem, boot from a live USB (Fedora Workstation Live, Ubuntu Live, or any distro’s live image) and work from there. Every second the system stays mounted read-write reduces recovery probability.

Recovering Deleted Files from ext4

ext4 remains the default filesystem on Debian, Ubuntu, Fedora, and most mainstream distributions. It also has the best recovery tool support of any Linux filesystem, because the ext4 journal and inode structures retain enough metadata to reconstruct deleted files - at least for a while.

extundelete - Your Best First Attempt

extundelete parses the ext4 journal to find deleted inode entries and reconstruct files. The original version (0.2.4, released 2013) still works on many systems, but a modernized fork called extundelete-ng supports the latest e2fsprogs (1.47+) and adds 64-bit block support for modern ext4 volumes.

Install and run it:

# Install from distro repos (original version)
sudo apt install extundelete    # Debian/Ubuntu
sudo dnf install extundelete    # Fedora

# Unmount the partition first
sudo umount /dev/sda1

# Recover all recently deleted files
sudo extundelete /dev/sda1 --restore-all

# Or recover a specific file by path
sudo extundelete /dev/sda1 --restore-file home/user/documents/report.pdf

Recovered files appear in a RECOVERED_FILES/ directory wherever you ran the command. extundelete works best within minutes of deletion on a quiet filesystem. It cannot recover files whose inodes have been reallocated, and it may not preserve original filenames if the directory entry has been overwritten.

debugfs - Targeted Inode Recovery

If you know the inode number of a deleted file (from running ls -i before deletion, or from log files), debugfs provides direct access to ext4 internals:

# Open the filesystem in debugfs
sudo debugfs /dev/sda1

# List recently deleted inodes with size and deletion time
debugfs: lsdel

# Dump a specific inode's data blocks to a file
debugfs: dump <inode_number> /recovery/myfile.pdf

This is precise but requires knowing which inode you want. The lsdel output shows deletion timestamps and file sizes, which helps identify the right inode when you do not have the number memorized.

ext4magic - Powerful but Abandoned

ext4magic was historically more capable than extundelete for complex recoveries, particularly when recovering entire directory trees with original permissions and timestamps. It could use journal transactions that extundelete missed, and it supported time-window-based recovery.

However, ext4magic was officially declared abandoned in January 2025. Over 30 releases of e2fsprogs have shipped since ext4magic was last updated, and the tool can no longer correctly parse modern ext4 filesystems. The project maintainer explicitly recommends against using it. If you find old guides recommending ext4magic, skip it and use extundelete or debugfs instead.

PhotoRec - The Last Resort That Always Works

When metadata-based recovery fails, PhotoRec (part of the TestDisk package, current stable version 7.2) ignores the filesystem entirely and scans raw disk sectors for file signatures - magic bytes in headers and footers that identify file types.

# Install TestDisk (includes PhotoRec)
sudo apt install testdisk

# Run PhotoRec on the partition
sudo photorec /dev/sda1

PhotoRec supports over 480 file formats including documents, images, databases, archives, and source code files. The tradeoff: recovered files lose their original names and directory structure, getting renamed by type and sequence number (e.g., f0001234.pdf). For large recoveries, expect to spend time sorting through thousands of generically named files.

PhotoRec partition selection interface showing disk and partition options
PhotoRec's text-based partition selection screen
Image: CGSecurity

A Step-by-Step ext4 Recovery Walkthrough

Imagine you just ran rm -rf ~/Documents on an ext4 partition. Here is the full recovery process:

  1. Stop everything. Do not close terminals, do not open new programs, do not run ls on the affected partition.

  2. Remount read-only (if /home is a separate partition):

    sudo mount -o remount,ro /home
  3. If /home is on the root partition, reboot from a live USB. On Ubuntu Live or Fedora Live, the internal drive will not be mounted by default.

  4. Identify the partition:

    lsblk -f
  5. Run extundelete:

    sudo extundelete /dev/sda2 --restore-all --after $(date -d "-1 hour" +%s)

    The --after flag limits recovery to files deleted in the last hour, reducing noise.

  6. Check the results in RECOVERED_FILES/. If your files are not there, try PhotoRec as a second pass.

  7. Copy recovered files to a different drive before remounting the original read-write.

PhotoRec recovery in progress showing file count and elapsed time
PhotoRec scanning a partition and recovering files in real time
Image: CGSecurity

Recovery Tool Comparison

ToolPreserves NamesPreserves StructureSpeedBest For
extundeleteSometimesNoFastRecent deletions, single files
debugfsNoNoFastKnown inode recovery
PhotoRecNoNoSlowCorrupted FS, any file type
ScalpelNoNoModerateTargeted file carving by type
ForemostNoNoModerateHeader/footer-based carving

Scalpel and Foremost are alternatives to PhotoRec that perform signature-based file carving. Scalpel supports multithreading for faster scanning. Foremost is older but well-documented for forensic use. In practice, PhotoRec covers the most file formats and is the best maintained of the three.

Recovering Deleted Files from Btrfs

Btrfs uses copy-on-write (COW) architecture, which means modified data is written to new disk locations rather than overwritten in place. This design makes traditional undelete tools useless - extundelete, which walks ext4 inode tables, produces garbage on Btrfs because the B-tree structure maps inodes to blocks in a completely different way.

On the other hand, Btrfs has built-in snapshot capabilities that make recovery straightforward when properly configured.

Snapshot Rollback - The Ideal Scenario

If you have automatic snapshots configured through snapper or btrbk , recovery is as simple as:

# List available snapshots
sudo snapper -c home list

# Restore a specific file from a snapshot
cp /.snapshots/42/snapshot/home/user/documents/report.pdf ~/recovered/

# Or undo all changes since a snapshot
sudo snapper -c home undochange 42..0

Btrfs snapshots are instant and use almost no additional disk space when created, because COW means only changed blocks after the snapshot are allocated separately. This is why having automatic snapshots is worth the negligible overhead.

What about performance impact? Creating a snapshot itself is nearly free. The concern comes from accumulating many snapshots on a heavily-written filesystem, where COW metadata can fragment and slow down operations over time. The fix is proper retention configuration - keep 24 hours of hourly snapshots and 7 days of daily snapshots, then let older ones get cleaned up automatically. Avoid enabling Btrfs quota groups (qgroups) for snapshot tracking, as they are known to degrade filesystem performance.

btrfs restore - When You Have No Snapshots

Without snapshots, recovery is harder but not impossible. btrfs restore reads the Btrfs metadata trees directly from the raw device and extracts files by walking older tree roots that have not yet been overwritten by the COW mechanism:

# Basic recovery to a separate drive
sudo btrfs restore /dev/sda1 /mnt/recovery/

# Use -s to search for older filesystem states
sudo btrfs restore -s /dev/sda1 /mnt/recovery/

# Use -i for case-insensitive path matching
sudo btrfs restore -si /dev/sda1 /mnt/recovery/

For deeply corrupted filesystems where the current superblock is damaged, btrfs-find-root can locate older tree root nodes:

# Find alternate root tree offsets
sudo btrfs-find-root /dev/sda1

# Use a specific offset with btrfs restore
sudo btrfs restore -t 293847562 /dev/sda1 /mnt/recovery/

PhotoRec also works on Btrfs partitions since it ignores filesystem structure entirely. It is your fallback when btrfs restore cannot find the files you need.

PhotoRec filesystem type selection showing ext2/ext3/ext4 and Other options
When running PhotoRec on Btrfs, select Other since it is not an ext filesystem
Image: CGSecurity

Setting Up Snapper for Automatic Snapshots

Given that Btrfs recovery without snapshots is difficult, configuring automatic snapshots should be a priority for any Btrfs user:

# Create a snapper config for /home
sudo snapper -c home create-config /home

# Edit the config for timeline snapshots
sudo nano /etc/snapper/configs/home

Key settings to configure:

TIMELINE_CREATE="yes"
TIMELINE_LIMIT_HOURLY="24"
TIMELINE_LIMIT_DAILY="7"
TIMELINE_LIMIT_WEEKLY="4"
TIMELINE_LIMIT_MONTHLY="0"
TIMELINE_LIMIT_YEARLY="0"

This creates hourly snapshots and retains 24 hours plus 7 days of history. On a typical desktop system, this adds a few hundred megabytes of overhead at most - far less than the cost of losing files.

What About Encrypted Partitions?

If your deleted files were on a LUKS -encrypted partition, recovery is still possible - but only if you have the passphrase or key file. The encryption layer sits between the recovery tools and the raw disk data, so you need to unlock the volume first:

# Open the LUKS volume
sudo cryptsetup luksOpen /dev/sda2 recoveryvolume

# Now run recovery tools against the decrypted mapper device
sudo extundelete /dev/mapper/recoveryvolume --restore-all

If you have lost the LUKS passphrase, the data is gone. There is no way to recover a LUKS passphrase, and brute-forcing modern LUKS2 key derivation (Argon2id) is computationally infeasible. Back up your LUKS headers with cryptsetup luksHeaderBackup - a corrupted header without a backup also means permanent data loss, even if you remember the passphrase.

How ext4’s Journal Affects Your Recovery Window

The ext4 journal is what makes metadata-based recovery possible, but it is also a ticking clock. The journal stores recent filesystem transactions - file creation, deletion, metadata changes - in a circular buffer. As new operations fill the journal, old entries get overwritten.

The practical recovery window depends on filesystem activity. On a quiet server with infrequent writes, journal entries for a deleted file might persist for days. On a busy desktop, they can be overwritten in minutes. The default ext4 journal size is 128 MB, which fills faster on systems with high write throughput.

A few things catch people off guard here:

  • Read operations do not destroy journal data by themselves, but background processes triggered by reads (like updatedb, file indexers, or atime updates) do write to the journal
  • On an active desktop, the recovery window is typically minutes. On a lightly used server, it can stretch to hours
  • Creating a journal image immediately after deletion freezes the recovery window: debugfs -R "dump_inode <8> /recovery/journal.img" /dev/sda1

This is why the “remount read-only immediately” advice is not optional - it is the single most important action you can take to maximize recovery chances.

Prevention: Trash, Snapshots, and Backups

The best time to deal with accidental deletion is before it happens. Three layers of protection address different failure modes.

Layer 1: Trash Integration for the Terminal

Install trash-cli to add a Freedesktop.org-compliant trash can to the command line:

# Install
sudo apt install trash-cli    # Debian/Ubuntu
pip install trash-cli          # Any distro via pip

# Use trash-put instead of rm
trash-put ~/documents/old-report.pdf

# List trashed files
trash-list

# Restore a file to its original location
trash-restore

# Empty the trash
trash-empty

Some guides recommend aliasing rm to trash-put in your .bashrc. This works for personal machines, but on shared servers it can surprise other administrators who expect rm to behave like rm. On servers, call trash-put explicitly.

Layer 2: Filesystem Snapshots

For Btrfs users, snapper or btrbk provide automatic snapshot management as described above. btrbk is lighter than snapper for server use and supports incremental send/receive to remote backup targets.

ext4 users do not get filesystem-level snapshots, but LVM snapshots provide similar functionality if your partitions sit on LVM:

# Create an LVM snapshot
sudo lvcreate --snapshot --size 5G --name home_snap /dev/vg0/home

# Mount and browse the snapshot
sudo mount /dev/vg0/home_snap /mnt/snapshot

An in-place conversion from ext4 to Btrfs is technically possible with btrfs-convert, but it carries real risk and should only be attempted with a full backup already in hand.

Layer 3: Offsite Backups with Restic

Restic (current version 0.18.x) provides fast, encrypted, deduplicated backups to local disks, SFTP servers, S3-compatible storage, and many other backends:

# Initialize a backup repository
restic -r sftp:user@backup-server:/repo init

# Back up /home
restic -r sftp:user@backup-server:/repo backup /home

# Restore a specific file from the latest snapshot
restic -r sftp:user@backup-server:/repo restore latest \
  --include /home/user/documents/report.pdf \
  --target /recovery/

Schedule backups with a systemd timer and you have automated offsite protection.

The 3-2-1 Rule Applied to Linux

The classic backup principle calls for 3 copies of your data, on 2 different types of media, with 1 copy offsite. A practical Linux implementation:

LayerWhatWhereRecovery Speed
Btrfs snapshotsPoint-in-time filesystem stateSame diskInstant
rsync to NASFile-level copyLocal network, different deviceMinutes
Restic to Backblaze B2Encrypted, deduplicated backupOffsite cloudMinutes to hours

Test your recovery plan regularly. Schedule a quarterly drill where you actually restore a test file from each layer. Verify that snapshot retention has not expired, that your NAS sync is current, and that restic prune has not removed the snapshots you would need.

When All Else Fails

If none of these tools recover your files, commercial data recovery services can sometimes extract data from drives at the hardware level - but expect to pay hundreds or thousands of dollars, and success is never guaranteed. For SSDs that have been TRIM’d, even professional services cannot help.

The better investment is prevention. Install trash-cli today, configure automatic snapshots if you run Btrfs, and set up restic or a similar backup tool pointed at a remote target. The few minutes that takes will save you from ever needing to read an article like this one in a cold sweat.