I would like to know how to delete a commit.
By delete
, I mean it is as if I didn't make that commit, and when I do a push in the future, my changes will not push to the remote branch.
I read git help, and I think the command I should use is git reset --hard HEAD
. Is this correct?
If you didn't publish changes, to remove latest commit, you can do
(note that this would also remove all uncommitted changes; use with care).
If you already published to-be-deleted commit, use git revert
If you want to keep the history, showing the commit and the revert, you should use:
enter the message explaining why are you reverting and then:
When you issue
git log
you'll see both the "wrong" commit and revert log messages.Reset on local branch
Force push to origin
If you have not yet pushed the commit anywhere, you can use
git rebase -i
to remove that commit. First, find out how far back that commit is (approximately). Then do:The
~N
means rebase the lastN
commits (N
must be a number, for exampleHEAD~10
). Then, you can edit the file that Git presents to you to delete the offending commit. On saving that file, Git will then rewrite all the following commits as if the one you deleted didn't exist.The Git Book has a good section on rebasing with pictures and examples.
Be careful with this though, because if you change something that you have pushed elsewhere, another approach will be needed unless you are planning to do a force push.
I referred both links below, It would be fine.
http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html https://gist.github.com/gunjanpatel/18f9e4d1eb609597c50c2118e416e6a6
Here's another way to do this:
Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree I right-clicked on the and selected "Reset BRANCHNAME to this commit". I think the command line is:
Since you just checked out your branch from remote, you're not going to have any local changes to worry about losing. But this would lose them if you did.
Then navigate to your repository's local directory and run this command:
This will erase all commits after the current one in your local repository but only for that one branch.