0
0
GitHow-ToBeginner · 3 min read

How to Use Git Reflog: Recover and Track Changes Easily

Use git reflog to see a log of all recent changes to your Git HEAD, including commits, resets, and checkouts. It helps you recover lost commits by showing their references, which you can use with git checkout or git reset.
📐

Syntax

The basic syntax of git reflog shows the history of HEAD changes. You can add options to filter or format the output.

  • git reflog: Shows the reflog of HEAD.
  • git reflog show <ref>: Shows reflog for a specific branch or reference.
  • git reflog expire: Cleans up old reflog entries.
  • git reflog delete: Deletes specific reflog entries.
bash
git reflog

git reflog show <ref>

git reflog expire --expire=now --all

git reflog delete --rewrite <ref>@{<index>}
💻

Example

This example shows how to use git reflog to find a lost commit and recover it by checking it out.

bash
git reflog
# Output shows recent HEAD changes with commit hashes

# Suppose you see a commit hash you want to recover, e.g., abc1234

git checkout abc1234
# This moves you to that commit so you can inspect or create a branch from it
Output
abc1234 HEAD@{0}: commit: Fix typo in README b7e9f2d HEAD@{1}: reset: moving to b7e9f2d 3f4a1c9 HEAD@{2}: commit: Add new feature ...
⚠️

Common Pitfalls

Many users forget that git reflog only tracks changes locally, so reflog entries are not shared with others. Also, reflog entries expire after 90 days by default, so act quickly to recover lost commits.

Another mistake is trying to use git reflog to recover commits that were never committed or pushed.

bash
## Wrong: expecting reflog to show remote changes
# git reflog origin/main
# This will not show reflog for remote branches

## Right: use reflog only on local refs
 git reflog show main
📊

Quick Reference

CommandDescription
git reflogShow recent HEAD changes
git reflog show Show reflog for a specific branch or ref
git checkout Recover or inspect a commit from reflog
git reflog expire --expire=now --allRemove old reflog entries
git reflog delete --rewrite @{}Delete specific reflog entry

Key Takeaways

Use git reflog to view all recent changes to HEAD and recover lost commits.
Reflog tracks only local changes and expires entries after 90 days by default.
You can recover commits by checking out or resetting to the commit hashes shown in reflog.
Reflog is a powerful safety net when you accidentally lose commits or reset branches.
Always act quickly to recover commits before reflog entries expire or get cleaned.