Michael
Michael

Reputation: 42050

How to change commit message of one of previous commits in Git?

I would like to change the commit message one of my previous commits. I guess I can

Unfortunately it did not work. After git commit --amend I do see the message changed but after git reset <my last commit id> I see the old unchanged commit message.

How can I change the commit message ?

Upvotes: 2

Views: 286

Answers (1)

MBlanc
MBlanc

Reputation: 1783

This can be done with rebase

  • git rebase -i <commit id>^ - Opens up a list of commits on your your $EDITOR. The caret at the end of the line is needed, since you need to specify the parent of the commit you want to edit.
  • Change the line pick <commit id> to reword <commit id>, save and close the file.

    r, reword = use commit, but edit the commit message

  • It will immediately re-open and load up the specified commit. Edit the message and save.

  • Note that this will change all subsequent commid ids! As with all other git objects, commit hashes are computed from its contents, and that includes the commit message.

Furthermore, you should understand the implications of rewriting history if you amend a commit that has already been published. For more information regarding rebase see http://git-scm.com/book/en/Git-Tools-Rewriting-History and https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html


Why git reset doesn't work

IMHO, the intesting part of this question is examining why your initial attempt did't work as expected. Basically it boils down to this: Commit objects are inmutable.

git reset B makes the branch point to a specific commit:

A -- B -- C -- D
     ^

git commit --ammend creates an alternate timeline:

A -- B -- C -- D
 \
  *- E
     ^

By moving back to the future with git reset D, the changes you made are discarded.

A -- B -- C -- D
 \             ^
  *- E

Upvotes: 3

Related Questions