Alex Cory Alex Cory - 2 months ago 6x
Git Question

How to cleanup git history removing certain commits?

What I'm trying to do:

I completed a feature.

git add -A; git commit -m "feature A complete"

Then I realized I missed some things.

git add -A; git commit -m "feature A missed something 1"
git add -A; git commit -m "feature A missed something 2"
git add -A; git commit -m "feature A missed something 3"

Now my history looks like this:

A238ad1 feature A missed something 3
3238adX feature A missed something 2
1238ad7 feature A missed something 1
111AAA2 feature A complete

I want it to look like this:

111AAA2 feature A complete

With all the
missed something
commits merged into the
feature A complete

I know
git rebase -i HEAD~4
is the right way to go, but it doesn't actually remove the bad commits to clean up the history.

I noticed in some other articles there's a
git commit --fixup
command and a
git rebase -i --autosquash
, but I'm not getting it to work properly. I'm sure this is super easy, I'm just out of it today.


In this case use interactive rebase

This can be initiated using

git rebase -i 

followed by number of heads you want to include

git rebase -i HEAD~5

where HEAD~5 indicates last 5 commits

Then you can use further options to squash your commits into one and edit the message. Just instead of pick option write squash instead


So here you see, I change option pick for s which is a shortcut for squash. When I save and close this file, interactive rebase will be initiated and commits which I indicated for squashing will be squashed into 21b4e04 Fixed missing bad practice. After squashing, it will ask you to enter a new commit message. Enter your new message and hit enter and you are done.

Here is a guide with an example