Git Reflog

Divya Srinivasan

 What is Git Reflog?

git reflog records updates to the tip of branches and to HEAD.
It keeps a local log of all changes—even those made by mistake—such as commits, resets, merges, and checkouts.
This makes it extremely useful for recovering lost commits or undoing unwanted changes.

When to Use Git Reflog

Use git reflog to:
  • Recover lost commits after a reset, rebase, or accidental deletion
  • Undo a hard reset or merge
  • See the full history of where your branch and HEAD have pointed, including operations not shown in git log

Show the Reflog

To view recent movements of HEAD and branches:

git reflog

Example output:

perl
e56ba1f (HEAD -> master) HEAD@{0}: commit: Revert "Just a regular update, definitely no accidents here..."
52418f7 HEAD@{1}: commit: Just a regular update, definitely no accidents here...
9a9add8 (origin/master) HEAD@{2}: commit: Added .gitignore
81912ba HEAD@{3}: commit: Corrected spelling error
3fdaa5b HEAD@{4}: merge: Merge pull request #1 from update-readme
836e5bf HEAD@{5}: commit: Updated readme for GitHub Branches

Each entry shows:
  • The commit hash
  • The reflog reference (e.g., HEAD@{2})
  • A brief description of what happened

Find and Recover Lost Commits

If you lose commits due to a hard reset or other destructive command, you can often recover them.

Example: Undo a Hard Reset

  • View recent HEAD positions:
git reflog
  • Find the commit you want to return to.
Suppose it’s at HEAD@{2}.
  • Reset your branch to that commit:
git reset --hard HEAD@{2}
This restores your branch to its previous state.

Clean Up the Reflog

By default, Git cleans old reflog entries automatically.
To manually remove older entries or force cleanup:
git reflog expire --expire=30.days refs/heads/main
git gc --prune=now
  • git reflog expire: Marks entries older than 30 days for deletion
  • git gc --prune=now: Runs garbage collection to remove them immediately

Tips & Best Practices

  • Use git reflog often to track your recent changes
  • Recover lost work or undo mistakes easily
  • Clean up old reflog entries periodically if your repository grows large

Troubleshooting

If you encounter problems:
  • Check the Git documentation
  • Search for specific error messages online
  • Ask in developer forums or Git communities

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send