← Back to Chapters

Git Reflog

? Git Reflog

? Quick Overview

Git reflog is a powerful Git command that allows you to view the history of the HEAD pointer and other references. It records actions like commits, resets, merges, and rebases, making it extremely useful for recovering lost commits or returning to previous states.

? Key Concepts

  • Tracks changes to HEAD and branch references
  • Works even when commits are no longer in history
  • Acts as a safety net for destructive Git operations

? Syntax / Theory

Basic syntax to view reflog:

? View Code Example
// Show the history of HEAD movements
git reflog

? Understanding Reflog Output

? View Code Example
// Sample reflog entry format
1234567 HEAD@{0}: commit: Commit message
  • 1234567 → Commit hash
  • HEAD@{0} → Most recent position of HEAD
  • commit → Action performed

♻️ Recovering Lost Commits

You can restore lost commits using the hash found in reflog.

? View Code Example
// Checkout a lost commit using its hash
git checkout 1234567
? View Code Example
// Restore commit by resetting HEAD
git reset --hard 1234567

? Undoing a Git Reset

? View Code Example
// Find the commit before reset
git reflog
? View Code Example
// Move HEAD back to previous state
git reset --hard abcdef1

? Use Cases

  • Recover deleted or reset commits
  • Undo rebase or merge mistakes
  • Track destructive Git operations

? Tips & Best Practices

  • Use reflog immediately after mistakes
  • Do not rely on reflog for long-term history
  • Clean old entries using git reflog expire

? Try It Yourself

  • Perform a hard reset and recover using reflog
  • Practice switching between HEAD states
  • Experiment with reflog expiration