Git: How to Undo commit *and* revert to last branch
Uh oh… I mistakenly committed a pretty complex change (including subdirectory and files renames) without really knowing what I am doing (or what Git would be doing).
I now want to undo everything such that:
- commit is completely reversed (as if
it has never been done, perhaps
removing it from history as well)
- Restore current working directory
.gitis) to a certain
branch (last one will do for now).
I found references to git reset –soft and git reset –hard but I have already proven to myself that I can do real damage by prematurely using a command without fully understanding it. 🙂
I found the git reset man page but I am still confused as to:
- What is
- What is the difference between
- In my situation (see above) do I
need to use
other (3 more options)?
- Do I need to run another command
git reset) to
“finalize” the reversal?
UPDATE: After reading the answer below:
- Do I understand correctly that all I
need to do in my situation is issue
a single command
git reset --hard?
- How do I verify that reversal was
2 Solutions collect form web for “Git: How to Undo commit *and* revert to last branch”
HEADis the latest commit of the checked-out branch.
masteris a branch (the main branch, by convention) whereas
HEADis a location in history for the checked-out branch.
HEADis relative to the branch you are on.
git reset --softwill leave your changes in the working tree, uncommitted for you to do whatever you like with.
git reset --hardwill restore the working tree to the state it was in at the commit you reset to.
- No other command is needed.
First, to keep the commit in case you want to inspect it later, make a branch:
git checkout -b my_bad_commit
(or alternatively do
git branch my_bad_commit as mentioned in larsman’s comment.)
Then return to
master or whatever branch you were on and reset:
git checkout branch_with_bad_commit git reset --hard HEAD^
HEAD^ translates to “the parent of HEAD,” which you can even stack for HEAD^^ = 2 commits back. For more on this topic, check the git community book chapter on undo in git
HEADis the tip of the current branch.
- The difference between
HEADchanges when you checkout a branch (or commit).
--softwill leave the changes around, so you can re-add/commit them or undo them by doing
git checkouton the changed files.
--hardwill reset the working area to the state of the commit you are resetting to.
- Not if you
reset --hard. You might have to
git push --forceto remote repos (although, if the changes you made are already on a remote, rewriting history is strongly discouraged).