Remove old git commits

Git

Git Problem Overview


I'm very new to git, and was wondering if something like this is possible?

>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.

Is this possible?

Git Solutions


Solution 1 - Git

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

Solution 2 - Git

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.

Solution 3 - Git

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

Solution 4 - Git

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshView Question on Stackoverflow
Solution 1 - GitShathurView Answer on Stackoverflow
Solution 2 - GitDeveView Answer on Stackoverflow
Solution 3 - GitrussoueView Answer on Stackoverflow
Solution 4 - GitAbandoned CartView Answer on Stackoverflow