I accidentally committed the wrong files to Git, but I haven't pushed the commit to the server yet.
How can I undo those commits from the local repository?
I accidentally committed the wrong files to Git, but I haven't pushed the commit to the server yet.
How can I undo those commits from the local repository?
How to fix the previous local commit
Use git-gui (or similar) to perform a
git commit --amend
. From the GUI you can add or remove individual files from the commit. You can also modify the commit message.How to undo the previous local commit
Just reset your branch to the previous location (for example, using
gitk
orgit rebase
). Then reapply your changes from a saved copy. After garbage collection in your local repository, it will be like the unwanted commit never happened. To do all of that in a single command, usegit reset HEAD~1
.Word of warning: Careless use of
git reset
is a good way to get your working copy into a confusing state. I recommend that Git novices avoid this if they can.How to undo a public commit
Perform a reverse cherry pick (git-revert) to undo the changes.
If you haven't yet pulled other changes onto your branch, you can simply do...
Then push your updated branch to the shared repository.
The commit history will show both commits, separately.
Advanced: Correction of the private branch in public repository
This can be dangerous -- be sure you have a local copy of the branch to repush.
Also note: You don't want to do this if someone else may be working on the branch.
Clean up your branch locally then repush...
In the normal case, you probably needn't worry about your private-branch commit history being pristine. Just push a followup commit (see 'How to undo a public commit' above), and later, do a squash-merge to hide the history.
If you have committed junk but not pushed,
OR
How to undo the last Git commit?
To restore everything back to the way it was prior to the last commit, we need to reset to the commit before HEAD.
If you don't want to keep your changes that you made:
If you want to keep your changes:
Now check your git log. It will show that our last commit has been removed.
Undo last commit:
git reset --soft HEAD^
orgit reset --soft HEAD~
This will undo the last commit.
Here
--soft
means reset into staging.HEAD~
orHEAD^
means to move to commit before HEAD.Replace last commit to new commit:
It will replace the last commit with the new commit.
A single command:
It works great to undo the last local commit!
On SourceTree (GUI for GitHub), you may right-click the commit and do a 'Reverse Commit'. This should undo your changes.
On the terminal:
You may alternatively use:
Or: