gitgit-rewrite-history

How do I modify a specific commit?


I have the following commit history:

  1. HEAD
  2. HEAD~
  3. HEAD~2
  4. HEAD~3

git commit --amend modifies the current HEAD commit. But how do I modify HEAD~3?


Solution

  • Use git rebase. For example, to modify commit bbc643cd, run:

    git rebase --interactive bbc643cd~
    

    Please note the tilde ~ at the end of the command, because you need to reapply commits on top of the previous commit of bbc643cd (i.e. bbc643cd~).

    In the default editor, modify pick to edit in the line mentioning bbc643cd.

    Save the file and exit. git will interpret and automatically execute the commands in the file. You will find yourself in the previous situation in which you just had created commit bbc643cd.

    At this point, bbc643cd is your last commit and you can easily amend it. Make your changes and then commit them with the command:

    git commit --all --amend --no-edit
    

    After that, return back to the previous HEAD commit using:

    git rebase --continue
    

    WARNING: Note that this will change the SHA-1 of that commit as well as all children -- in other words, this rewrites the history from that point forward. You can break repos doing this if you push using the command git push --force.