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.
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
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.