gitgithub

Replace a commit in git


I have a bad commit from a long time ago, I want to remove it completely from git history as if it never happened. I know the commit id let's say 1f020. I have tried git rebase and remove it , but there is so many conflicts when rebasing that it is not possible that way. That commit is a simple 1 line change of code and pushing some files not related to the project. So I want to write that 1 line code change and commit it, then replace somehow replace this new commit with the one a long time ago.


Solution

  • If the offending commit is in a private repository, what you want to do is not a big deal. Rewriting published git history is irritating for your collaborators, so be sure removing this line is worth the cost.

    The git-rebase documentation has a helpful passage.

    git rebase [...] [<--onto newbase>] [<upstream>] [<branch>]
    

    A range of commits could also be removed with rebase. If we have the following situation:

    E---F---G---H---I---J  topicA
    

    then the command

    git rebase --onto topicA~5 topicA~3 topicA
    

    would result in the removal of commits F and G:

    E---H'---I'---J'  topicA
    

    This is useful if F and G were flawed in some way, or should not be part of topicA. Note that the argument to --onto and the upstream parameter can be any valid commit-ish.

    Assuming your history is linear and the offending commit is in your master branch, you can adapt the example above by running

    git rebase --onto 1f020~ 1f020 master
    

    For hairier situations, use interactive rebase. You may find it helpful to follow along with an example that merges two commits, but instead of marking the commit with s for squash, remove the entire line to remove the commit from your history.