How to remove old commit from git

2020-09-09

I'm writing this as a letter for my future self who will forget how to do it by the time I need it again. Info is from this StackOverflow question.

I very oftenly make a new branch from a feature branch, instead of first checking out the main branch. This then makes the commits from the feature branch show up in the new one, which I normally don't want.

How to use git rebase to remove a commit after branching from another branch

For example, let's imagine that old-branch is two commits ahead from the trunk.

* aa4075c - (HEAD -> old-branch, origin/old-branch) More work on some feature
* 1e51926 - Some feature
* ddda45a - (origin/master) Some change
* cd4dc47 - Initial commit

Side note: Use the following to get a nicer view of git log.

git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s     %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

And now you create a branch, without first checking out master by running git checkout -b new-branch, and commit some changes, you get the following:

* bcb25e6 - (HEAD -> new-branch) A different feature
* aa4075c - (origin/old-branch) More work on some feature
* 1e51926 - Some feature
* ddda45a - (origin/master) Some change
* cd4dc47 - Initial commit

Oh no! If you now open a PR with new-branch you'll get the changes from old-branch too!

To fix this, just run git rebase -i HEAD~3. Your editor of choice will open with the following:

pick bcb25e6 A different feature
pick aa4075c More work on some feature
pick 1e51926 Some feature

You can now replace the last two commits to have drop, which will remove them from new-branch while leaving your latest commit intact. Also important, this won't affect old-branch at all, which will keep the two commits as they are.

pick bcb25e6 A different feature
drop aa4075c More work on some feature
drop 1e51926 Some feature

Save and exit, and done! new-branch now looks like it should!

* 4b7d78e - (HEAD -> new-branch) A different feature
* ddda45a - (origin/master) Some change
* cd4dc47 - Initial commit