Git & GitHub ยท Chapter 38 of 42

git reflog

`git reflog` records every change to the tip of your branches, even ones that aren't visible in `git log`, such as resets, rebases, and checked-out commits. It's a safety net for recovering 'lost' work.

Because reflog tracks where HEAD has pointed over time, you can use it to find and recover commits after an accidental hard reset or a botched rebase.

Syntax
git reflog
git reset --hard HEAD@{2}

Viewing the reflog

Run `git reflog` to see a list of recent HEAD movements, each with a reference like HEAD@{1} and a short description of the action that caused it.

Recovering lost commits

Once you find the commit hash you need in the reflog, use `git reset --hard commit-hash` or `git cherry-pick commit-hash` to recover it.

Example 1 (bash)
git reflog
Output
9c2e1aa HEAD@{0}: commit: Fix crash when cart is empty
a3f5c9e HEAD@{1}: reset: moving to a3f5c9e

Shows recent HEAD movements, including a reset, which can help find 'lost' commits.

Example 2 (bash)
git reset --hard HEAD@{1}
Output
HEAD is now at a3f5c9e Add login validation

Recovers the repository state from before an earlier reset, using the reflog reference.

Key points

  • git reflog tracks all movements of HEAD, even 'invisible' ones.
  • It's a safety net for recovering commits lost after reset or rebase.
  • Reflog entries are local only and eventually expire.
  • You can reset or cherry-pick using reflog references like HEAD@{1}.
๐Ÿ’ก Note: Reflog is one of Git's best safety features โ€” very few mistakes in Git are truly unrecoverable while reflog entries still exist.

๐Ÿ“ Quick Quiz

1. What does git reflog track?

2. Why is reflog useful?

3. Are reflog entries shared when you push to GitHub?