DEV Community

Cesar Vega
Cesar Vega

Posted on

Fixing (and removing) commits in a git branch for beginners.

We have all been there. You want to merge and have a different set of commits that you want to have. Maybe you rebased a branch you shouldn't have or checked out from the wrong branch. But don't worry, fixing it is easy.

In this article, I will show a few techniques to get your branch exactly how you want it and avoid merging code and commits that do not belong in your target branch.

Let's start with an example where we have four commits:
git log --oneline

c761a8f (HEAD -> my-feature) commit-3
e056796 bad-commit-1
269a02d commit-2
ceaab87 commit-1
Enter fullscreen mode Exit fullscreen mode

We can see that a bad commit snuck into our branch, so how do we fix it?
It's simple: First, we make sure the commit is unnecessary and want to remove it.
We can do this with:

git show e056796
or
git diff e056796^!

And then, we can see what our commit did.

Pro tip: This command will look prettier if you have customized your terminal with tools like ohMyZSH
Enter fullscreen mode Exit fullscreen mode

Our second step is to take that commit out of our history. I do this by rebasing our branch. We would do an interactive rebase to our target branch in our example.

git rebase -i target-branch

An editor (often Vim or Nano) will open, showing the last commits. It'll look something like this:

pick ceaab87 commit-1
pick 269a02d commit-2
pick e056796 bad-commit-1
pick c761a8f commit-3
Enter fullscreen mode Exit fullscreen mode

So, to keep the commits we want, delete the line corresponding to the bad commit (bad-commit-1):


pick ceaab87 commit-1
pick 269a02d commit-2
pick c761a8f commit-3
Enter fullscreen mode Exit fullscreen mode

Exit and save the file.

Pro tip: For Vim, press "i" to interact with the text. And then, you click "ESC" -> "wq" to save and exit.
Enter fullscreen mode Exit fullscreen mode

Finally, if you've already pushed your branch to a remote repository before this change, you'll need to force push your changes:

git push origin your-branch-name --force-with-lease

And now you have a clean branch without all those pesky commits. Always double-check with your team if those commits are unnecessary, and remember that this will only affect YOUR branch, so don't be too scared to go through the process.

Top comments (0)