0
0
GitConceptBeginner · 3 min read

What is git reflog: Understanding Git Reference Logs

git reflog is a Git command that records updates to the tip of branches and other references. It lets you see a history of where your branches and HEAD have pointed, helping you recover lost commits or undo mistakes.
⚙️

How It Works

Imagine your Git branches and HEAD as bookmarks in a book. Every time you move a bookmark to a new page, git reflog writes down that move in a notebook. This notebook keeps track of all the recent changes to your branch pointers, even if those changes are not part of the official commit history.

This means if you accidentally delete a branch or reset to an earlier commit, you can look in this notebook to find where your branch or HEAD used to point. It records every change locally, so you can safely explore or fix mistakes without losing work.

💻

Example

This example shows how git reflog lists recent HEAD movements, including commits and resets.

bash
git init example-repo
cd example-repo
echo "First" > file.txt
git add file.txt
git commit -m "First commit"
echo "Second" >> file.txt
git add file.txt
git commit -m "Second commit"
git reset --hard HEAD~1
git reflog
Output
e8a1f2d (HEAD -> master) HEAD@{0}: reset: moving to HEAD~1 b7c3a1f HEAD@{1}: commit: Second commit a1d2c3b HEAD@{2}: commit (initial): First commit
🎯

When to Use

Use git reflog when you need to find lost commits or undo changes that are not visible in the normal commit history. For example, if you accidentally reset or deleted a branch, git reflog helps you find the commit hashes to restore your work.

It is also useful for tracking your recent branch movements and understanding what happened during complex rebases or merges.

Key Points

  • Local history: reflog records changes only on your local machine.
  • Recovery tool: helps recover lost commits and branches.
  • Tracks HEAD: shows where HEAD and branches pointed over time.
  • Temporary: reflog entries expire after 90 days by default.

Key Takeaways

git reflog tracks all recent changes to branch tips and HEAD locally.
It helps recover lost commits after resets or branch deletions.
Use reflog to find commit hashes not visible in normal history.
Reflog entries expire after about 90 days by default.
It is a powerful safety net for undoing mistakes in Git.