Quick answer: to undo your last local Git commit but keep the changes on disk, run
git reset HEAD~1. To undo the commit and throw the changes away completely, run
git reset --hard HEAD~1. Neither command touches a remote unless you push afterward.
The problem
You ran git commit too early — wrong files staged, a typo in the message, or you just
changed your mind — and you haven't pushed yet. Git makes this completely reversible because a
local commit is just a pointer; nothing is "lost" until you overwrite or garbage-collect it.
Method 1: Keep your changes, undo the commit (most common)
git reset HEAD~1
This moves the branch pointer back one commit and unstages the files, but leaves your edits sitting in the working directory exactly as they were. Use this when you just want to re-stage things differently or fix the commit message before recommitting.
Method 2: Keep changes staged
git reset --soft HEAD~1
--soft rewinds the branch pointer but leaves everything staged, so a plain
git commit immediately reproduces the same change set with a new message.
Method 3: Discard everything (destructive)
git reset --hard HEAD~1
This deletes the commit and resets your working files to match the previous commit. Only use
this if you genuinely don't want the changes anymore — there's no undo for uncommitted work lost this
way (though the commit itself is usually recoverable via git reflog for a while).
What if I already pushed?
If the commit is already on a shared remote, resetting locally and force-pushing rewrites history for
everyone else who pulled it. Prefer git revert <commit> instead, which creates a new
commit that undoes the changes without rewriting history.
FAQ
Does git reset delete my files?
Only with --hard. Plain git reset or --soft leave your files
untouched on disk.
Can I recover a commit after git reset --hard?
Usually yes, for a limited time. Run git reflog to find the commit's SHA, then
git checkout <sha> or git reset --hard <sha> to bring it back.
What's the difference between HEAD~1 and HEAD^?
They're equivalent for a normal single-parent commit. HEAD^ can trip up Windows/DOS and
zsh shells because of how they treat ^, so HEAD~1 is the safer, portable form.
No comments
Post a Comment