NOTE: If the commit has been posted, and the repository is used by others, it is highly recommended NOT to delete the commit. Instead, you can "reverse" the commit with the "git revert" command" (see this response).
The default to delete or edit an old commit is to use an interactive rebase.
For example, if you want to delete the commit with 1ca0fcd hash:
git rebase -i 1ca0fcd~1
This command will open VIM with the commit list after 1ca0fcd (inclusive).
Example of a repository of mine:
pick 1ca0fcd Exposed HttpClient and JsonSerializerSettings through the IJSendClient interface
pick a65278f Updated README to mention CompositeMessageInterceptor
pick cec16d6 Released version 0.3.0
pick 3cdea37 Added link to release notes to nuspecs
pick c862a21 Changed IJSendParser and DefaultJSendParser to use JsonSerializerSettings
# Rebase ddc2139..c862a21 onto ddc2139
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
To delete a commit, simply delete the line from that commit (as indicated in the instructions - "If you remove a line here THAT COMMIT WILL BE LOST"). Then write :wq
to record and exit VIM, and the interactive rebase will:
- delete commit 1ca0fcd and all commits after 1ca0fcd
- rewrite all commits after 1ca0fcd
It is possible that when re-writing commits conflicts occur. In this case the rebase will pause, ask you to resolve conflicts, and then continue using git rebase --continue
.
Read more: 7.6 Git Tools - Rewriting History
I thought the two were the same command, only with different types of instructions, in which case errors you get in each of the commands?
– Guilherme Nascimento
Oh it gives some conflict errors, I think the old commit files don’t even exist anymore, but in case of the question I wanted to know if this is the most usual method to delete a commit
– haykou
So, as I said, as far as I know both commands are the same, only differentiates by the type of instruction you went through to identify, the first I think is
safe
and the other is normal, but the instruction is the same.– Guilherme Nascimento