Being able to go back is the whole reason to use Git. But how you go back depends on the situation. Here are the four you’ll actually use, with a danger rating.
Which one to use
| What you want | Command | Danger |
|---|---|---|
| Throw away edits and return to the last commit | git restore filename | High (edits are gone) |
Undo a git add | git restore --staged filename | Low |
| Fix the message on your last commit | git commit --amend | Medium |
| Cancel out an earlier commit | git revert commit-id | Low |
Only the first one truly destroys anything. Let’s take them in order.
1. Throw away edits: git restore
For “I tried a bunch of things and I want none of it.”
git restore style.cssstyle.css returns to its state at the last commit. To undo everything in the folder:
git restore .2. Undo an add: git restore —staged
For “I put it in the box, but it doesn’t belong in this record.”
git restore --staged script.jsWith --staged, it’s only taken out of the box — your edits are untouched. Safe to use freely.
Helpfully, git status tells you about both:
Changes to be committed:
(use "git restore --staged <file>..." to unstage) ← take out of the box
Changes not staged for commit:
(use "git restore <file>..." to discard changes) ← throw away editsGit shows you the commands available right now. “When in doubt, git status” applies here too.
3. Fix your last commit: git commit —amend
For when you notice a typo in the message, or a forgotten file, right after committing.
git commit --amend -m "Add the favorites list"Your last commit is overwritten with the new message. If you forgot a file, git add it first and run the same command to fold it into that same commit.
4. Cancel an earlier commit: git revert
For “the change three commits back is what broke it.” First find the commit ID:
git log --onelinec3d4e5f Change the send button color
b2c3d4e Add the form behavior
a1b2c3d Build the page skeletonThen name the commit you want to cancel:
git revert b2c3d4eGit stacks on a new commit that undoes that one’s changes. The history isn’t erased, and the fact that you undid it is recorded too — which is exactly why it’s safe.
You can skip git reset for now
Search around and you’ll meet git reset --hard. It’s a powerful command that rewinds the history itself, and pointing it at the wrong place erases work in bulk.
As a beginner, the four above cover nearly everything. Just know that the stronger tool exists, and look it up when you truly need it.
Summary of this lesson
git restorethrows away edits — it can’t be undone, so check the target firstgit restore --stagedundoes an add. Your edits survive, so it’s safe- Fix the last commit with
--amend(before pushing); cancel a pushed commit withgit revert