删除旧的 git 提交

我是新来的,想知道这样的事情是否可能发生?

>git log --pretty=oneline --abbrev-commit
2f05aba Added new feature
3371cec Fixed screw up    <-- I want to remove this
daed25c Screw up          <-- and remove this.
e2b2a84 First.                So it's like they never happend.

这可能吗?

119599 次浏览

This is possible with git rebase. Try the following

git rebase -i HEAD~4

and then, follow the interactive instructions in your editor. In the first step you "squash" the commits. It should look something like this:

pick 2f05aba ... will be preserved
squash 3371cec ... will be squashed with daed25c
squash daed25c ... will be squashed with e2b2a84
pick e2b2a84 .. will contain this and 3371cec and daed25c

In the second step you can edit the commit messages.

If you truly wish to delete them (wiping them from history, never to be seen any more), you can

run rebase:

git rebase -i HEAD~4

and then, just delete (or comment out) the lines corresponding to the commits you wish to delete, like so:

pick 2f05aba ... #will be preserved
#pick 3371cec ... #will be deleted
#pick daed25c ... #will be deleted
pick e2b2a84 ... #will be preserved

Squash is useful when you want to generate a list of merged commits under a single hash, but if you are looking to take three separate commits and have a final output that looks like it was a single commit, I recommend fixup

git rebase -i HEAD~4

pick 2f05aba ... will be preserved
fixup 3371cec ... will be merged with daed25c
fixup daed25c ... will be merged with e2b2a84
pick e2b2a84 .. will include 3371cec and daed25c, but only the commit message of e2b2a84

You can find more information in the command list of the interactive rebase UI.

To completely delete commit(s) there is a new option drop for git interactive rebases now. First run:

git rebase -i HEAD~4

Then replace pick with drop for the commit(s) to be dropped:

pick 2f05aba ... #will be preserved
drop 3371cec ... #will be dropped
drop daed25c ... #will be dropped
pick e2b2a84 ... #will be preserved

This worked on Fedora for me with the following version:

$ git version
git version 2.21.0

Most of the time I face the same issue, i use below command to delete old commits and sync with server

git reset --hard HEAD~1
git push -f

Side Note: HEAD~1 will delete the last commit HEAD~5 will delete last 5 commits push -f is force push so that copies in server (github/bitbucket/other) is also deleted