I sure that there is at least once time in the life of a programmer, they need to delete a commit in the history of a branch. So I write this post to share you the way to delete a commit from branch in Git.
My example is we have a git log tree as below:
1 2 3 4 5 6 7 8 |
/tmp/test$ git log --graph --all --oneline --decorate * 16ab9a2 (HEAD, dev) Commit B1 * 077795b Commit A1 | * 9dec2b5 (master) Commit D |/ * ea61baa Commit C * 786219e Commit B * 2fa7d48 Commit A |
And you are working on branh DEV, you need to remote “Commit C” from branch DEV. So you should use command git rebase -i
1 |
git rebase -i ea61baa^ |
In there, “ea61baa” is the hash key of “Commit C”. After entering the command, a editor will be opened with the content below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
pick ea61baa Commit C pick 077795b Commit A1 pick 16ab9a2 Commit B1 # Rebase 786219e..16ab9a2 onto 786219e # # 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. # # Note that empty commits are commented out |
You have to remove line
1 |
pick ea61baa Commit C |
After that, save it.
You are done, just re-check by git log command
1 2 3 4 5 6 7 8 |
/tmp/test$ git log --graph --all --oneline --decorate * f8814f4 (HEAD, dev) Commit B1 * 1377c45 Commit A1 | * 9dec2b5 (master) Commit D | * ea61baa Commit C |/ * 786219e Commit B * 2fa7d48 Commit A |
You can see that “Commit C” now is not in branch dev.