Git: how do I undo my last commit?

asked 5 months ago175 viewsen

0

I committed the wrong files. I haven't pushed yet. How do I undo it without losing my changes? And what if I *had* pushed?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

2 Answers

9
✓
✓ Accepted answer

Not pushed yet: move the branch back one commit and keep your changes staged:

git reset --soft HEAD~1

- --soft keeps the changes staged. - --mixed (the default) keeps them, unstaged. - --hard throws them away. Be careful.

If you only need to fix the commit (add a forgotten file, change the message):

git add forgotten.js
git commit --amend

Already pushed to a shared branch: don't rewrite history others may have pulled. Create a new commit that reverses it:

git revert <commit-sha>
git push

Safety net: git reflog lists every position HEAD has been at, so even after a --hard reset you can usually recover with git reset --hard <sha-from-reflog>.

Sign in to tell others whether this worked.

answered 5 months ago
0

If you just want to unstage files you added by mistake (not undo a commit): git restore --staged <file>. And git restore <file> discards uncommitted changes to a file. Careful, that one is not recoverable.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.