Skip to content

Latest commit

 

History

History
316 lines (196 loc) · 3.91 KB

File metadata and controls

316 lines (196 loc) · 3.91 KB

🕵️ Git Reflog (Recover Lost Work)

Recover commits, branches, and lost work using Git's hidden history.


📌 What Is Git Reflog?

git reflog shows:

A log of all HEAD movements (your Git activity history)


🧠 Why Reflog Is Powerful

Even if you:

  • delete a branch ❌
  • reset commits ❌
  • lose changes ❌

👉 Reflog can recover them.


🗺️ Big Picture

flowchart LR
    A[Commits] --> B[HEAD Moves]
    B --> C[Reflog Records]
    C --> D[Recover Lost Work]
Loading

🧬 What Reflog Tracks

- commits
- checkouts
- resets
- rebases
- merges

🧱 Basic Command

git reflog

🔍 Example Output

a1b2c3 HEAD@{0}: commit: fix bug
d4e5f6 HEAD@{1}: checkout: moving to feature
g7h8i9 HEAD@{2}: commit: add feature

🧠 Key Concept

Reflog is:

Local only
Temporary (expires)
Hidden safety net

🧪 Real-World Scenario

1. You commit work
2. You accidentally run git reset --hard
3. Work seems gone
4. Use reflog → recover commit

🧱 Recover Lost Commit


Step 1 — View reflog

git reflog

Step 2 — Identify commit

HEAD@{2}

Step 3 — Recover

git checkout HEAD@{2}

OR:

git reset --hard HEAD@{2}

🧬 Internal Behavior

Git stores:

HEAD movements → reflog entries

🧠 HEAD Movement

HEAD → current commit pointer

Every time HEAD moves:

👉 Reflog records it


🔄 Visual Flow

Commit A → Commit B → Commit C
        ↑
     HEAD moves

Reflog tracks all moves

🧪 Recover Deleted Branch

git reflog

Find commit → recreate branch:

git checkout -b recovered-branch <commit-hash>

🧪 Recover After Reset

git reset --hard HEAD~2

Oops 😱

Recover:

git reflog
git reset --hard HEAD@{1}

⚠️ Important Notes


Reflog is local

Not shared with remote.


Reflog expires

default ~90 days

🚨 Common Mistakes


❌ Not using reflog after mistake

Many think work is lost forever.


❌ Using reset incorrectly

Reflog helps recover.


❌ Ignoring commit hashes


✅ Best Practices

  • use reflog for recovery
  • act quickly before expiration
  • combine with log for clarity
  • understand HEAD movement

🧠 Reflog vs Log

Reflog Log
shows history of HEAD shows commit history
includes lost commits only reachable commits

🎤 Interview Questions

What is git reflog?

Tracks HEAD movement history.


Can reflog recover deleted commits?

Yes (if not expired).


Is reflog shared?

No, it is local.


Difference between log and reflog?

Log shows commits, reflog shows actions.


🧪 Practice Lab

# create commit
echo "test" >> file.txt
git commit -am "test commit"

# reset
git reset --hard HEAD~1

# recover
git reflog
git reset --hard HEAD@{1}

🎯 Final Takeaway

Reflog is your safety net.

It allows you to:

  • recover lost commits
  • undo mistakes
  • debug history

👉 Next Step

➡️ 04-git-bisect.md