DEV Community

Kolawole O. Gabriel
Kolawole O. Gabriel

Posted on


Getting rid of specific git commits

There are two possible reasons (that I can think of) you might want to revert a commit or specific commits:

Scenario A: When working on a feature branch and you later realize a specific change is no longer relevant and you want to remove such commit/change.

Scenario B: When you pushed a working branch to remote, just about to a create a pull request, you compared your branch and realize you have commits that are not related to your work, probably due to the local repository being out of sync.

How to fix ?

In the case of Scenario A; we can execute the following:

git revert <commit-hash>

where <commit-hash> is the targeted commit hash, done.

Hint, we can list all commits together with their hash by executing

git log --oneline

Scenario B: where we need to remove multiple commits/changes from our branch, we can rebase interactively with a target base branch by executing

git rebase -i <target-branch>

This will result into an opened editor listing all the commits in the current working branch.

Hint, rebase entails taking the current changes and stacking it on top of another branch, hence we can selectively pick the commits desired and reject others.

With the editor opened, we can go ahead and remove specific commits as desired by simply deleting their records in the opened editor. There are instructions as to applicable commands in the editor.

The opened editor with commands, should look like this:

# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit

On completing the exercise and closing the editor, the rebase will work its way automatically.

That is it. Fun coding!

Top comments (0)