Git reflog

Git reflog

Git Reflog: Recover Lost Commits & Undo Mistakes

git reflog (Reference Log) is a lifesaver when you need to recover lost commits, undo mistakes, or track branch movements.

Unlike git log, which shows commit history, git reflog tracks all changes to HEAD, even if commits are lost or branches are deleted.

1. Viewing the Reflog

Run:

git reflog

Example output:

a1b2c3d HEAD@{0}: commit: Added new feature d4e5f6g HEAD@{1}: commit: Fixed a bug h7i8j9k HEAD@{2}: reset: moving to HEAD~1 l0m1n2o HEAD@{3}: rebase (finish): returning to main

🔹 HEAD@{0} is the most recent state.
🔹 Each entry shows what happened, such as commits, resets, or rebases.


2. Recovering Lost Commits

If you accidentally reset or deleted commits, find the commit hash using:

git reflog

Then, reset your branch back to that commit:

git reset --hard <commit-hash>

3. Undoing a Reset or Checkout

3.1 Undo a Hard Reset

If you ran:

git reset --hard HEAD~2

and lost commits, restore them with:

git reset --hard HEAD@{1}

3.2 Undo a Checkout

If you mistakenly switched branches:

git reflog git checkout HEAD@{1}

4. Using git reflog with Branches

4.1 Recover a Deleted Branch

If you deleted a branch but need to restore it:

git reflog git checkout -b deleted-branch <commit-hash>

5. Clean Up Reflog

Old entries are automatically deleted, but you can clean them manually:

git reflog expire --expire=30.days.ago --all git gc --prune=30.days.ago

Conclusion

ActionCommand
View refloggit reflog
Recover a lost commitgit reset --hard <commit-hash>
Undo a resetgit reset --hard HEAD@{1}
Recover a deleted branchgit checkout -b branch-name <commit-hash>
Clean old reflog entriesgit reflog expire --expire=30.days.ago --all

🔹 git reflog is your safety net in Git! Need more details? 🚀

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close