Fixing the last commit: --amend
Committed, then noticed a typo in the message or a file you forgot? --amend redoes the most recent commit:
$ git commit --amend -m "Add pancake recipe with photo"Stage a forgotten file first and it gets folded in:
$ git add photo.jpg
$ git commit --amend -m "Add pancake recipe with photo"One caution to file away: amend doesn't edit the old commit, it replaces it with a brand-new commit that has a different hash. That's harmless while the commit only exists on your machine. Once you've shared commits with teammates (unit 7), replacing shared history causes real trouble, a rule we'll formalize in unit 9.
Practice the amend. You just committed "Add pancake recipe" and immediately realized photo.jpg belonged in that commit.
Step 1/3: Stage the forgotten file.
Undoing an old commit safely: revert
reset rewinds history, which is fine for commits nobody else has seen. For anything older or already shared, use git revert:
$ git revert a1b2c3d
[main f0e9d8c] Revert "Add pancake recipe"Revert doesn't delete anything. It creates a new commit containing the opposite changes (every added line removed, every removed line re-added). History stays intact and honest: the mistake happened, and here's the commit that fixed it.
git reset | git revert | |
|---|---|---|
| What it does | erases commits from the end of history | adds a new commit that cancels an old one |
| History | rewritten | preserved |
| Safe on shared work | no | yes |
Quiz
A bad commit from last week is already on your team's shared history. How do you undo its effect?
The safety net: git reflog
Here's the secret that makes Git nearly panic-proof: even "destroyed" commits usually still exist. git reflog prints a local log that records every position HEAD has ever had on your machine — every commit, reset, switch, and merge moved HEAD, and each move was written down. (Think of it as Git's private diary.)
$ git reflog
f0e9d8c HEAD@{0}: reset: moving to HEAD~1
c7d8e9f HEAD@{1}: commit: Add photo of finished pancakes
a1b2c3d HEAD@{2}: commit: Add pancake recipeSuppose that reset was a terrible mistake and c7d8e9f held real work. It's no longer in git log, but the reflog still knows its hash, so git reset --hard c7d8e9f brings it right back.
Limits: the reflog is local to your machine and entries expire after around 90 days. It rescues committed work. Changes you never committed remain the one thing Git cannot resurrect, which is the deepest argument for committing early and often.
Problem
You reset --hard one commit too far and a finished feature vanished from git log. Which command shows you every place HEAD has been, so you can find the lost commit's hash?