Course outline · 0% complete

0/28 lessons0%

Course overview →

git reset: rewinding commits

lesson 4-2 · ~11 min · 11/28

Taking back a commit

git restore handles uncommitted changes. What if you already committed and regret it? git reset moves your current position, HEAD from lesson 3-1, back to an earlier commit.

First, the address notation: HEAD~1 means "one commit before HEAD", HEAD~2 means two before, and so on. So the everyday incantation is:

$ git reset --soft HEAD~1

read as "move me back one commit." The commit disappears from git log, but the changes inside it don't vanish into thin air. Where they land depends on the mode flag, and that's the entire trick to understanding reset.

working directorystaging arearepository--soft--mixed(default)--hard
How far each reset mode reaches. --soft only rewrites history, --mixed also clears the staging area, --hard additionally overwrites your working directory. Longer bar, more destruction.

The three modes

CommandHistoryStaging areaWorking directory
git reset --soft HEAD~1rewoundkeeps the changes, stageduntouched
git reset HEAD~1 (mixed, default)rewoundclearedkeeps the changes, unstaged
git reset --hard HEAD~1rewoundclearedoverwritten, changes gone

Memory hook: soft is the gentlest landing (everything still staged, ready to re-commit), mixed drops the changes back to your desk, hard throws them in the shredder.

--hard is the second dangerous command of the unit. Before running it, say out loud what you expect to lose. (Lesson 4-3 reveals a safety net that can often save you anyway.)

Worked example: re-slicing a bad commit

Here is the reset engineers actually run weekly. You hurried and committed two unrelated changes as one blob:

$ git log --oneline
9c8b7a6 wip stuff        ← a bug fix AND a new recipe, mashed together
a1b2c3d Add pancake recipe

Lesson 2-3's rule says one logical change per commit, so unpack it:

$ git reset HEAD~1        # mixed: commit undone, both changes back, unstaged
$ git add soup.txt
$ git commit -m "Fix soup salt amount"
$ git add cake.txt
$ git commit -m "Add chocolate cake recipe"

The sloppy commit is gone and two clean, honest commits stand in its place. Nothing was ever at risk: mixed reset never touches the working directory, it only rewinds history and clears the staging area so you can re-stage in better slices.

Quiz

Which reset mode discards your uncommitted file contents along with rewinding the commit?

Quiz

In git reset --soft HEAD~1, what does HEAD~1 refer to?

Problem

You committed too early and want to add one more file to the same change. You decide to undo the commit but keep everything staged so you can re-commit in a moment. Which mode flag do you give git reset?