Delete and completely remove the commit from git history

感情迁移 提交于 2019-12-04 11:56:16

You can interactively rewrite history with git rebase -i:

git rebase HEAD~6 -i 

Will open your editor and allow you to either squash multiple commits into one, or completely remove them from history (by deleting the line for those commits in your editor.) The ~6 means rewrite the last 6 commits, the -i means do it interactively. In your case, you'll want to remove the lines that say "pick 1c4a11a" and "pick b4ab3c".

Note that the most recent commit in the editor that gets launched is the last line, not the first one, and since you're rewriting history and you've already pushed, you'll also have to "git push --force", not just "git push" in order to send your changes upstream.

You can use interactive rebase in order to go back in your commit history and do things differently. For using interactive rebase, just:

git rebase -i <commit_id>

<commit_id> is the parent of the last commit you want to edit. After executing this command, just put d or drop in front of commits you're gonna delete or even delete the line corresponding to that commit.

Running this command gives you a list of commits in your text editor that looks something like this:

pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# 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

The interactive rebase gives you a script that it’s going to run. It will start at the commit you specify on the command line and replay the changes introduced in each of these commits from top to bottom. It lists the oldest at the top, rather than the newest, because that’s the first one it will replay.

But since you've pushed the branch to your upstream repository, do communicate this history rewrite to your possible colleagues, as the git documentation says:

Remember again that this is a rebasing command – every commit included in the range will be rewritten, whether you change the message or not. Don’t include any commit you’ve already pushed to a central server – doing so will confuse other developers by providing an alternate version of the same change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!