World map

 

BM: Baca dalam Bahasa Melayu

World 11: Rescue Center

I lost commits after reset

You will learn: how to bring commits back after a hard reset.

The problem

main and HEAD jump back two commits. Add day 2 entry and Add day 3 entry turn into dashed, lost dots.
6d3a9b1a8feb63270a76ebcf4670031ae57

Oops. One git reset --hard HEAD~2, and two days of diary vanished. Breathe. This happens to everyone. Here’s the safe way out.

Try it

Day 2 and day 3 were commits. Can Git bring them back?

Pick one answer.

Watch

git reflog: HEAD@{0} is the reset. HEAD@{1} is commit: Add day 3 entry. Terminal output: $ git reflog 270a76e (HEAD -> main) HEAD@{0}: reset: moving to HEAD~2 031ae57 HEAD@{1}: commit: Add day 3 entry bcf4670 HEAD@{2}: commit: Add day 2 entry 270a76e (HEAD -> main) HEAD@{3}: commit: Add style a8feb63 HEAD@{4}: commit: Add day 1 page 6d3a9b1 HEAD@{5}: commit (initial): Add README

git reflog lists every move HEAD made. HEAD@{1} is where you were just before the reset.

Try it

Jump back to just before the reset.

6d3a9b1a8feb63270a76ebcf4670031ae57

Check

Put the rescue steps in order, first at the top.

First step at the top. Put these in order. Use the arrows, or drag.

  • git reflog: find the line before the reset
  • git log --oneline: check the commits are back
  • git reset --hard HEAD@{1}
  • git status: check nothing is uncommitted

You did it!

You can now bring commits back after a hard reset.

Go deeper (optional)

Extra careful? git branch rescue HEAD@{1} only puts a label on the lost commit. Nothing moves, nothing is wiped. Right after a reset, ORIG_HEAD also points where you were. Changes you never committed can’t come back. Commit often!