Have you ever needed to merge a branch but exclude certain changes that aren’t ready yet? This shouldn’t happen super often, but on bigger projects you’ll probably run into something like this. Luckily with Git, there is always a way. Even if you’re not an advanced Git user, this trick should be fairly straightforward to implement. It utilizes
git rebase, which rewrites your commit history. Git’s rebase feature is used in many ways to rewrite history, including removing single commits. Let’s get into how this works
git rebase -i <commit id>~1
If you want to only remove one commit, get the commit ID through
git log and replace
<commit id> with the actual ID. If you want to remove multiple commits, get the ID of the commit that’s the latest in the history. The list shown will be from your commit ID to the most recent commit ID(head).
In the picture above, I entered
7c675ca in the command, and
3e77a8e is the most recent commit for this branch. From here, removing commits is easy. To remove a commit, comment out the line (put a
# in front of it). You can remove as many lines as you want, or just a single one. Once you’ve done that, save the revision (
CRTL+X if you’re using the default nano editor).
Since this rebase is interactive using the
-i flag, git will go through each commit that needs an action and you will run
git rebase --continue when you are done with it. A common example is a merge conflict, which you will solve by manually editing the files, running
git add . and then
git rebase --continue. Once these commits are taken care of, your history will successfully be rewritten! In some cases, you may not need to do anything at all. Pretty simple, right?
When I ran into this issue on a project, some googling led me to this post.