Git & GitHub Course
Git & GitHub
/
Advanced

git reflog

Definition

The Reference Logs record when the tips of branches and other references were updated in the local repository. It is the ultimate safety net.

Explain Like I'm New

Git secretly records every single time your `HEAD` pointer moves. Did you accidentally run `git reset --hard` and permanently delete 5 commits? `git log` says they are gone. But `git reflog` has a secret backup list of where you were before you made the mistake.

Real World Example

You do a messy Interactive Rebase, accidentally delete an entire feature, and panic. You type `git reflog`, find the hash of where you were 5 minutes ago, and `git reset --hard` back to it, restoring everything.

Common Use Cases

  • •Recovering 'lost' commits
  • •Undoing a bad rebase or reset

Terminal Output

bash / terminal
# Oh no! I accidentally hard reset and lost my work! $ git reset --hard HEAD~3 # 1. Open the secret diary of my actions $ git reflog /* Output: a1b2c3d HEAD@{0}: reset: moving to HEAD~3 9f8e7d6 HEAD@{1}: commit: Add shopping cart <--- I WANT THIS BACK! 5e4d3c2 HEAD@{2}: commit: Update CSS */ # 2. Travel back to the moment before I messed up $ git reset --hard 9f8e7d6 # Everything is completely restored!

Interview Questions

basic

  • Does the reflog sync to GitHub when you push?

intermediate

  • How long does Git keep items in the reflog before permanently deleting them?

Flash Cards

Question

Sync to GitHub?

Click to reveal answer
Answer

NO. The reflog is strictly local to your specific laptop. It is a log of YOUR actions.

Question

How long?

Click to reveal answer
Answer

By default, unreachable commits in the reflog expire after 30 days. After that, Git's 'Garbage Collector' permanently deletes them from your hard drive.