← Back to Chapters

Git Recovery

? Git Recovery

? Quick Overview

Git is a powerful version control system, but sometimes mistakes happen. Whether it’s accidentally deleting files, losing commits, or making unwanted changes, Git provides several ways to recover lost work and fix errors.

? Key Concepts

  • Recovering lost commits
  • Restoring deleted files
  • Undoing staged and unstaged changes
  • Safe vs destructive recovery commands

? What is Git Recovery?

Git recovery refers to methods used to recover lost commits, restore files, or undo undesired changes using Git’s history and internal references.

? Recovering Lost Commits

Using Git Reflog

git reflog shows the history of HEAD movements and helps recover commits removed from branch history.

? View Code Example
// Show history of HEAD movements
git reflog
? View Code Example
// Reset repository back to a lost commit
git reset --hard abc1234

Using Git Checkout with New Branch

? View Code Example
// Create a recovery branch from lost commit
git checkout -b recovery-branch abc1234

? Recovering Deleted Files

Restore File from Commit

? View Code Example
// Restore a deleted file from a specific commit
git checkout <commit-hash> <path-to-file>

Recover Staged Files

? View Code Example
// Discard changes and restore last committed version
git checkout -- <file-name>

↩️ Undoing Changes in Git

Undo Unstaged Changes

? View Code Example
// Revert file to last committed state
git checkout -- <file-name>

Undo Staged Changes

? View Code Example
// Unstage file without losing changes
git reset <file-name>

Undo Last Commit

? View Code Example
// Undo last commit but keep changes staged
git reset --soft HEAD~1

⚠️ Using Git Reset for Recovery

? View Code Example
// Completely reset repository to a commit
git reset --hard <commit-hash>

? Interactive Git Recovery Flow

Commit Reset Recover

? Use Cases

  • Recovering accidentally deleted commits
  • Restoring files removed by mistake
  • Undoing experimental changes safely

? Tips & Best Practices

  • Use git reflog before assuming data is lost
  • Avoid frequent use of git reset --hard
  • Create backup branches before risky operations

? Try It Yourself

  • Delete a file and restore it using checkout
  • Reset a commit and recover it with reflog
  • Compare soft vs hard reset behavior